1

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);
   });
});
Lin Du
  • 88,126
  • 95
  • 281
  • 483
lomse
  • 4,045
  • 6
  • 47
  • 68
  • 1
    It seems you just add [Runtime request handler](https://mswjs.io/docs/api/setup-server/use#runtime-request-handler) using `server.use()` method. But there is no graphql client call it. – Lin Du Apr 14 '22 at 03:27
  • You are right :) – lomse Sep 10 '22 at 20:38

0 Answers0