I have been trying to mock my graphql-request with vitest. The request looks this way:
const getTastyFruit = gql`
query Fruit($id: String!) {
fruit(id: $id) {
shop {
shopId
}
}
}
`;
This request is part of a bigger picture. Let's go top down. I have a lambda, which sits on an API Gateway Endpoint. This lambda calls a TropicalWorld
client. This client has plenty of methods, one of those: CheckIfFruitIsReallyTasty
. It's a private async methof of my TropicalWorld
class (client).
CheckIfFruitIsReallyTasty
initialises a new graphql client.
const fruitsClient = new GraphQLClient(
"https://www.tastyfruits.com",
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
Then my query comes in play:
const getTastyFruit = gql`
query Fruit($id: String!) {
fruit(id: $id) {
shop {
shopId
}
}
}
`;
Then there is a try catch block which basically awats a response from the query:
const response= await fruitsClient.request(getTastyFruit, {
id,
});
I was really trying different approaches, to mock this graphql requiest with vitest, but whatever I do, I get the error ERROR status code: 404, status text: undefined
vi.mock('graphql-request', () => ({
GraphQLClient: class {
request = vi.fn();
},
gql: (text: string) => text,
}));
This indicates, that my client still makes requests to the graphql server. The only thing I am really interested in is the repsonse, whoch I really wish to mock, so I can test happy path and the error path. But as I said, vitest graphql mocking isn't really working for me. Any ideas?
The Error came from a different place in my test code. Generally I found a great way to mock graphql in the official vitest documentation. I had to install msw for this though...
import { afterAll, afterEach, beforeAll } from 'vitest'
import { setupServer } from 'msw/node'
import { HttpResponse, graphql, http } from 'msw'
const posts = [
{
userId: 1,
id: 1,
title: 'first post title',
body: 'first post body',
},
// ...
]
export const restHandlers = [
http.get('https://rest-endpoint.example/path/to/posts', () => {
return HttpResponse.json(posts)
}),
]
const graphqlHandlers = [
graphql.query('ListPosts', () => {
return HttpResponse.json(
{
data: { posts },
},
)
}),
]
const server = setupServer(...restHandlers, ...graphqlHandlers)
// Start server before all tests
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
// Close server after all tests
afterAll(() => server.close())
// Reset handlers after each test `important for test isolation`
afterEach(() => server.resetHandlers())
here is the link