How to mock the external library graphql-request call using jest

How to mock the external library graphql-request call using jest


0

I’m encountering difficulties while writing Jest unit tests for a module that interacts with graphql-request.

Here’s the test

import { jest } from '@jest/globals';
import { request } from 'graphql-request';
import {
  logActivityPhoneCallScheduled,
} from './candidateService';

jest.mock('graphql-request', () => {
  return {
    request: jest.fn(),
  };
});

beforeEach(() => {
  jest.clearAllMocks();
});

test('scheduled', async () => {
  request.mockResolvedValue({ addCandidateActivity: { id: 835 } });

  const now = Date.now();
  const input = {
    candidateId: 'TBX-001',
    eventId: 305,
    userId: 'y29d13lkcas91',
    userIsStaff: true,
    scheduledFor: new Date(now + 14 * 24 * 60 * 60 * 1e3).toISOString(),
    createdAt: new Date(now - 905 * 1e3).toISOString(),
  };

  const expectedActivity = {
    candidateId: 'TBX-001',
    type: 'SCHEDULE',
    action: 'scheduled',
    newValue: '305',
    additionalPayload: {
      type: 'phonecall',
      scheduled_at: input.scheduledFor,
    },
    userId: 'y29d13lkcas91',
    userIsStaff: true,
    createdAt: input.createdAt,
  };

  const result = await logActivityPhoneCallScheduled(input);

  expect(result).toBe(835);
  expect(request).toHaveBeenCalledTimes(1);
  expect(request.mock.calls[0][0]).toBe('https://candidate-service:5000');
  expect(request.mock.calls[0][1]).toContain('addCandidateActivity');
  expect(request.mock.calls[0][2]).toEqual({ activity: expectedActivity });
});

Despite my efforts, I keep encountering errors like

TypeError: request.mockResolvedValue is not a function

      18 |
      19 | test('scheduled', async () => {
    > 20 |   request.mockResolvedValue({ addCandidateActivity: { id: 835 } });
         |           ^
      21 |
      22 |   const now = Date.now();
      23 |   const input = {

I suspect the issue lies in how I’m trying to mock the graphql-request module and its request function.

Could someone please guide me on the correct approach to mock requests made using graphql-request for local testing within Jest? What might be causing the errors I’m facing, and how can I resolve them?

Share
Improve this question


Load 7 more related questions


Show fewer related questions

0

Reset to default



Leave a Reply

Your email address will not be published. Required fields are marked *