msw: graphql operation doesn't get intercepted

813 Views Asked by At

Using MWS, I'm trying to mock the graphql operation testRequest as follows:

Funny thing is, the console.log in the graphql.query('testRequest', (_, res, ctx)=> {...}) block never gets invoked while the operation name is valid. What could be the issue?

type TestRequestItem = TestRequestQuery['testRequest'];

const testRequestBuilder = build<TestRequestItem>({
   fields: {
      profession: { name: 'Engineer' },
      location: { name: 'New York'},
      __typename: 'TestRequest',
   }
});

const server = setupServer();

const testRequestQuery = (payload: TestRequestQuery) => {
   return server.use(
      graphql.query<TestRequestQuery, TestRequestQueryVariables>('testRequest', (req, res, ctx) => {
          console.log('response: ', ctx.data(payload)) //This console log never gets invoked and there
          return res(ctx.data(payload))
      }),
   );
}

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));

afterEach(() => {
   server.resetHandlers();
   jest.clearAllMocks();
});

// Clean up after the tests are finished.
afterAll(() => server.close());

describe.only('testing a component', () => {
   it.only('should do something awesome', async () => {
      const item = testRequestBuilder();

      testRequestQuery({ testRequest: item });
      expect(true).toBe(true);
   });
});
0

There are 0 best solutions below