我如何在玩笑中全局模拟lodash / deep函数

时间:2019-12-12 06:14:38

标签: jestjs lodash

我正在控制器中使用lodash / deep函数。在对控制器执行笑话测试时,会出现以下错误: 所有的lodash函数都会出错。

  

TypeError:cloneDeep_1。默认不是函数。

下面的示例代码

::after

1 个答案:

答案 0 :(得分:0)

我想您想在cloneDeep函数上添加一个间谍。但是没必要,cloneDeep函数是纯函数,不会调用任何副作用的外部服务。因此,您无需为其模拟或存根。

index.ts

import cloneDeep from 'lodash/cloneDeep';

export class SomeClass {
  public static transformBoardBasicInfo(rawBoard: any): any {
    const clonedBoard: any = cloneDeep(rawBoard) as any;
    clonedBoard.info = this.getInfo(rawBoard);
    return clonedBoard;
  }

  public static getInfo(board) {
    return '';
  }
}

index.spec.ts

import { SomeClass } from './';
import cloneDeep from 'lodash/cloneDeep';

jest.mock('lodash/cloneDeep', () => jest.fn());

describe('main', () => {
  afterEach(() => {
    jest.restoreAllMocks();
    jest.resetAllMocks();
  });
  it('should pass', () => {
    jest.spyOn(SomeClass, 'getInfo');
    (cloneDeep as any).mockImplementationOnce((data) => {
      return require.requireActual('lodash/cloneDeep')(data);
    });
    const mRawBoard = { info: '123' };
    const actual = SomeClass.transformBoardBasicInfo(mRawBoard);
    expect(actual).toEqual({ info: '' });
    expect(cloneDeep).toBeCalledWith(mRawBoard);
    expect(SomeClass.getInfo).toBeCalledWith(mRawBoard);
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/59298693/index.spec.ts
  main
    ✓ should pass (25ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.075s, estimated 12s