2 years ago
#7909
sajad.sharhani
Mocking GraphQL API with MSW for Testing
I'm trying to mock graphql API for testing react app but facing a problem
the handler is:
import { graphql } from 'msw'
export const postsGql = [
{
userId: 1,
id: 1,
title: 'first post title',
body: 'first post body',
},
{
userId: 2,
id: 5,
title: 'second post title',
body: 'second post body',
}
]
Define handlers that catch the corresponding requests and returns the mock data.
export const graphqlHandlers = [
graphql.query('posts', async(req, res, ctx) => {
return res(
ctx.data(
postsGql,
),
)
}),
]
my test file:
it('Should return posts when clicking fetch with graphql button', async() => {
render(<ApolloProvider client={client}>
<App />
</ApolloProvider>)
expect(screen.getByRole('heading', { name: 'MSW Testing Library Example', level: 1 })).toBeDefined()
userEvent.click(screen.getByRole('button', { name: 'Fetch Posts GraphQL' }))
await waitForElementToBeRemoved(() => screen.queryByLabelText('loading'))
postsGql.forEach((posts) => {
expect(screen.getByRole('heading', { name: posts.title, level: 2 })).toBeDefined()
expect(screen.getByText(posts.body)).toBeDefined()
})
})
but faced this error:
Missing field 'posts' while writing result [
{
"userId": 1,
"id": 1,
"title": "first post title",
"body": "first post body"
},
{
"userId": 2,
"id": 5,
"title": "second post title",
"body": "second post body"
}
]
I will appreciate any kind of help thanks
testing
graphql
msw
0 Answers
Your Answer