[英]How to spy/mock minimatch with jest
我知道如何使用 jest 模擬/監視 ES6 導入,但我想到了這個:
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));
我的測試失敗了所有上述模擬方法。
您不能在測試用例功能范圍內使用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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.