DEV Community

Discussion on: How to mock an imported Typescript class with Jest

Collapse
 
soullivaneuh profile image
Sullivan SENECHAL

I try to mock a FeathersJS service class with your article example without any success.

I cannot figure out how to check class methods calls.

I ended up an another way with this:

import { mocked } from 'ts-jest/utils';
import app from '../../src/app';
import { Notifications } from '../../src/services/notifications/notifications.class';
import { NotificationsData } from '../../src/types';

jest.mock('../../src/services/notifications/notifications.class');
const mockNotificationsService = mocked(Notifications, true);
const mockNotificationsCreate = mocked(mockNotificationsService.mock.instances[0].create)
mockNotificationsCreate.mockImplementation(() => Promise.resolve({} as NotificationsData));

beforeEach(() => {
  // Clear registered calls from older tests.
  mockNotificationsCreate.mockClear();
})

describe('\'foo\' service', () => {
  it(
    'mock implement test',
    () => {
      return app.service('foo').create({ foo: 'bar' })
        .then(() => {
          expect(mockNotificationsCreate).toBeCalledTimes(1);
          expect(mockNotificationsCreate).toHaveBeenNthCalledWith(1, {
            applicationSlug: 'kidways',
            body: 'body',
            title: 'title',
            userIds: [
              'user1'
            ]
          }, {});
        })
    },
  );

  it(
    'mock implement test second',
    () => {
      return app.service('foo').create({ foo: 42 })
        .then(() => {
          expect(mockNotificationsCreate).toBeCalledTimes(2);
          expect(mockNotificationsCreate).toHaveBeenNthCalledWith(1, {
            applicationSlug: 'slug',
            body: 'body',
            title: 'title',
            userIds: [
              'user1'
            ]
          }, {});
          expect(mockNotificationsCreate).toHaveBeenNthCalledWith(2, {
            applicationSlug: 'slug',
            body: '42',
            title: 'title',
            userIds: [
              'user1'
            ]
          }, {});
        })
    },
  );
});
Enter fullscreen mode Exit fullscreen mode

This works but the implements looks wrong. I have to first mock the whole class with jest.mock then mock one of the method while storing it on a variable for test check.

Is it the way to go? Will you do the same way?

Thanks!