0
0
GraphQLquery~30 mins

Resolver unit tests in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Resolver Unit Tests for GraphQL
📖 Scenario: You are building a simple GraphQL API for a bookstore. You want to make sure your resolver functions work correctly by writing unit tests for them.
🎯 Goal: Write unit tests for GraphQL resolvers that fetch book data from a mock database.
📋 What You'll Learn
Create a mock data array called books with 3 book objects
Create a configuration variable called bookIdToTest with the value 2
Write a resolver function called getBookById that returns the book matching bookIdToTest
Write a unit test function called testGetBookById that asserts the resolver returns the correct book
💡 Why This Matters
🌍 Real World
Unit testing GraphQL resolvers helps catch bugs early and ensures your API returns correct data.
💼 Career
Writing and testing resolvers is a key skill for backend developers working with GraphQL APIs.
Progress0 / 4 steps
1
Create mock book data
Create a list called books with exactly these three book objects: { id: 1, title: "1984", author: "George Orwell" }, { id: 2, title: "Brave New World", author: "Aldous Huxley" }, and { id: 3, title: "Fahrenheit 451", author: "Ray Bradbury" }.
GraphQL
Need a hint?

Use an array of objects with the exact keys and values given.

2
Add test book ID configuration
Create a constant called bookIdToTest and set it to the number 2.
GraphQL
Need a hint?

Use const bookIdToTest = 2; exactly.

3
Write the resolver function
Write a function called getBookById that takes no parameters and returns the book object from books where id equals bookIdToTest. Use the find method.
GraphQL
Need a hint?

Use books.find(book => book.id === bookIdToTest) inside the function.

4
Write the unit test function
Write a function called testGetBookById that calls getBookById() and checks if the returned book's title is exactly "Brave New World". Use an if statement to compare and throw an error with the message "Test failed" if it does not match.
GraphQL
Need a hint?

Call getBookById(), check the title, and throw an error if it is wrong.