Skip to content

Instantly share code, notes, and snippets.

@filipfilipovich
Created May 26, 2023 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save filipfilipovich/7d060b38164a73effe17ad076c207a66 to your computer and use it in GitHub Desktop.
Save filipfilipovich/7d060b38164a73effe17ad076c207a66 to your computer and use it in GitHub Desktop.
Books API endpoint test file
<?php
use App\Models\Book;
const API_ENDPOINT = '/api/books';
uses()->group('books'); // Assign 'books' group to all tests (whole file)
beforeEach(function () {
$this->mockBooksCollection = Book::factory(5)->create(); // Generate mock database entries for testing
});
test('get books', function () {
$response = $this->get(API_ENDPOINT);
expect($response->getStatusCode())
->toBe(200)
->and($response->getContent())->json()
->toHaveCount($this->mockBooksCollection->count());
});
test('get books by filter', function () {
$this->mockBooksCollection = $this->mockBooksCollection->merge(
Book::factory($mockCount = 2)->create([$mockFilter = 'author' => $mockAuthor = 'John Doe'])
);
$response = $this->get(sprintf('%s?%s=%s', API_ENDPOINT, $mockFilter, $mockAuthor));
expect($response->getStatusCode())
->toBe(200)
->and($response->getContent())->json()
->toHaveCount($mockCount)
->each(function ($book) use ($mockAuthor) {
$book->author->toBe($mockAuthor);
});
});
test('get book by ISBN', function () {
$this->mockBooksCollection = $this->mockBooksCollection->add(
Book::factory()->create(['isbn' => $mockIsbn = '1234567890'])
);
$response = $this->get(sprintf('%s/%s', API_ENDPOINT, $mockIsbn));
expect($response->getStatusCode())
->toBe(200)
->and($response->getContent())->json()->isbn
->toBe($mockIsbn);
});
test('invalid route', function () {
$response = $this->get(sprintf('%s/%s', API_ENDPOINT, 'test'));
expect($response->getStatusCode())
->toBe(404);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment