Home > Mobile >  Jest Mock Class - Implementation as imported module
Jest Mock Class - Implementation as imported module

Time:06-03

I'm trying to mock a contructor of a class from an imported module. It works if my mock implementation is inlined into the jest.mock() factory function, but not if the implementation is imported from another file.

This works:

test.ts:


jest.mock('external-lib', () => {
  const originalModule = jest.requireActual('@external-lib');

  function ClassMock(): any {
    return {
      method1: (val: number): Promise<any> => {
        return Promise.resolve({ a: val });
      },
    };
  }

  return {
    __esModule: true,
    ...originalModule,
    StrategyComputation: jest.fn(ClassMock),
  };
});

This does not work

If I take the function ClassMock out into another file mocks.ts and import it in the test file, it does not work:

test.ts:

import { ClassMock } from './mocks'; 

jest.mock('external-lib', () => {
  const originalModule = jest.requireActual('@external-lib');

  return {
    __esModule: true,
    ...originalModule,
    StrategyComputation: jest.fn(ClassMock),
  };
});

mocks.ts:

  export function ClassMock(): any {
    return {
      method1: (val: number): Promise<any> => {
        return Promise.resolve({ a: val });
      },
    };
  }

If fails with a

TypeError: Cannot read property 'ClassMock' of undefined

CodePudding user response:

One option is to keep the function() {} inside the mock factory, and import the class methods implementations only:

test.ts:

import { MockFunctions } from './mocks'; 

jest.mock('external-lib', () => {
  const originalModule = jest.requireActual('@external-lib');

  return {
    __esModule: true,
    ...originalModule,
    StrategyComputation: jest.fn(function() {
        return MockFunctions
    }),
  };
});

mocks.ts:

  export const MockFunctions = {
    method1: (val: number): Promise<any> => {
      return Promise.resolve({ a: val });
    },
  }

CodePudding user response:

This is what I did for mock. It's a lot easier.

import Axios, { AxiosRequestConfig } from 'axios';

describe('MyClass', () => {
  it('test doSomething', async () => {
    const axios = Axios as jest.Mocked<typeof Axios>;
    axios.request.mockResolvedValue({});

    const result = new MyClass().doSomething();

    expect(result).toBeTruthy();
  });
});
  • Related