我知道如何使用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));我的测试使用上面所有的模拟方法都失败了。
发布于 2020-02-24 15:45:16
您不能在测试用例功能范围内使用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();
});
});https://stackoverflow.com/questions/60350522
复制相似问题