I want to test my graphql queries and mutations using Jest. I am writing my unit tests as given in Apollo docs:
describe('Tests', () => {
let testServer;
beforeAll(() => {
testServer = new ApolloServer({ typeDefs, resolvers });
});
// Below test passes
it('should return matching result for the movies query', async () => {
const limit = 3;
const query = `
query {
movies(limit: ${limit}) {
id
name
}
}
`;
const result = await testServer.executeOperation({ query });
expect(result.data.movies.length).toBe(limit);
});
// Below test fails.
it('should mark movie as watched using the markWatched mutation', async () => {
const movieIds = [9873, 8754];
const mutation = `
mutation {
markWatched(movieIds: ${movieIds}) {
id,
watched
}
}
`;
const result = await testServer.executeOperation({ query: mutation });
expect(result.data.markWatched).toBe([
{
id: 9873,
watched: true
},
{
id: 8754,
watched: true
}
]);
});
});
// Mutation
type Mutation {
markWatched(ids: [ID]!): [Movies]!
}
// Resolver
Mutation:
{
markWatched: (_, { ids }) =>
markMoviesAsWatched(ids)
}
// Data model (which is simply a local file exporting an array - moviesData in below code)
const markMoviesAsWatched = ids => {
const response = [];
moviesData.forEach(movie => {
if (ids.includes(movie.id)) {
movie.watched = true;
response.push(movie);
}
});
return response;
};
The first test regarding query is passing while the second test regarding mutation is failing with error: TypeError: Cannot read properties of undefined (reading 'markWatched')
. The exact mutation runs fine in Apollo playground. Not sure what's wrong with my mutation test?
from Mutation test failing with executeOperation (Apollo Graphql)
No comments:
Post a Comment