简体   繁体   中英

Jest Mock Class - Implementation as imported module

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

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 });
    },
  }

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

import Axios, { AxiosRequestConfig } from 'axios';

jest.mock('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();
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM