Created
May 26, 2023 12:28
-
-
Save filipfilipovich/7d060b38164a73effe17ad076c207a66 to your computer and use it in GitHub Desktop.
Books API endpoint test file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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