Skip to content

Commit 6697e92

Browse files
committed
test: make book tests self-contained (not dependent on seed data)
1 parent 20f0a5d commit 6697e92

File tree

1 file changed

+26
-7
lines changed

1 file changed

+26
-7
lines changed

src/schema/books/booksSchema.test.js

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,24 @@ const getResult = (response) => {
1313
return response.body.singleResult
1414
}
1515

16+
// Helper to create a test book via mutation
17+
const createTestBook = async (title = `Test Book ${Date.now()}`, author = 'Test Author') => {
18+
const mutation = gql`
19+
mutation AddBook($title: String, $author: String) {
20+
addBook(title: $title, author: $author) {
21+
id
22+
title
23+
author
24+
}
25+
}
26+
`
27+
const response = await server.executeOperation({
28+
query: mutation,
29+
variables: { title, author }
30+
})
31+
return getResult(response).data.addBook
32+
}
33+
1634
// Clean up after all tests
1735
test.after.always(async () => {
1836
await client.$disconnect()
@@ -55,6 +73,9 @@ test('books query returns an array', async t => {
5573
})
5674

5775
test('books query returns books with correct structure', async t => {
76+
// Ensure at least one book exists
77+
await createTestBook('Structure Test Book', 'Structure Author')
78+
5879
const query = gql`
5980
query {
6081
books {
@@ -77,13 +98,9 @@ test('books query returns books with correct structure', async t => {
7798
})
7899

79100
test('book query returns a single book by id', async t => {
80-
// First get a valid book id
81-
const listQuery = gql`{ books { id } }`
82-
const listResponse = await server.executeOperation({ query: listQuery })
83-
const listResult = getResult(listResponse)
84-
const bookId = listResult.data.books[0]?.id
85-
86-
t.truthy(bookId, 'Need at least one book in DB for this test')
101+
// Create a book to query
102+
const createdBook = await createTestBook('Single Query Test', 'Query Author')
103+
const bookId = createdBook.id
87104

88105
const query = gql`
89106
query GetBook($id: ID!) {
@@ -103,6 +120,8 @@ test('book query returns a single book by id', async t => {
103120
t.falsy(result.errors, 'book query returned errors')
104121
t.truthy(result.data?.book, 'book query should return a book')
105122
t.is(result.data.book.id, bookId, 'Returned book should have the requested id')
123+
t.is(result.data.book.title, 'Single Query Test')
124+
t.is(result.data.book.author, 'Query Author')
106125
})
107126

108127
test('book query returns null for non-existent id', async t => {

0 commit comments

Comments
 (0)