如何用玩笑窥探/嘲笑迷你搭配

时间:2020-02-22 08:51:25

标签: javascript typescript unit-testing mocking jestjs

我知道如何mock/spy an ES6 import with jest,但是这个问题困扰了我

my-module.ts

import minimatch from 'minimatch';

export function foo(pattern: string, str: string): boolean {
  return minimatch(pattern, str);
}

test.ts

describe('minimatch', () => {
  it('should call minimatch', () => {
    const mock = jest.fn().mockReturnValue(true);
    jest.mock('minimatch', mock);

    foo('*', 'hello');

    expect(mock).toHaveBeenCalled();
  });
});

我还尝试过以其他方式进行嘲讽:

import * as minimatch from 'minimatch';
// ...
const mock = jest.fn().mockReturnValue(true);
(minimatch as any).default = mock;

甚至

import {mockModule} from '../../../../../../test/ts/utils/jest-utils';
// ...
const mock = jest.fn().mockReturnValue(true);
const originalModule = jest.requireActual('minimatch');
jest.mock('minimatch', () => Object.assign({}, originalModule, mockModule));

我的测试因上述所有模拟方法而失败。

1 个答案:

答案 0 :(得分:0)

您不能在测试用例功能范围内使用jest.mock()。您应该在模块范围内使用它。

例如 my-module.ts

import minimatch from 'minimatch';

export function foo(pattern: string, str: string): boolean {
  return minimatch(pattern, str);
}

my-module.test.ts

import { foo } from './my-module';
import minimatch from 'minimatch';

jest.mock('minimatch', () => jest.fn());

describe('minimatch', () => {
  it('should call minimatch', () => {
    foo('*', 'hello');
    expect(minimatch).toHaveBeenCalled();
  });
});

单元测试结果覆盖率100%:

 PASS  stackoverflow/60350522/my-module.test.ts
  minimatch
    ✓ should call minimatch (6ms)

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

如果要在测试用例中模拟模块,则应使用jest.doMock(moduleName, factory, options)

例如

my-module.test.ts

describe('minimatch', () => {
  it('should call minimatch', () => {
    jest.doMock('minimatch', () => jest.fn());
    const { foo } = require('./my-module');
    const minimatch = require('minimatch');
    foo('*', 'hello');
    expect(minimatch).toHaveBeenCalled();
  });
});