javascript - 如何用玩笑来监视/模拟 minimatch
问题描述
我知道如何用 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();
});
});
推荐阅读
- c# - Selenium Chromedriver 在使用 WebDriverWait 直到 findelement 时不等待并抛出 ElementNotFound
- javascript - 时刻获取星期几的语言环境
- java - 如何在不知道总流大小的情况下将 InputStream 拆分为多个 BoundedInputStream?
- c++ - 标准::向量
::insert 和 std::move_iterator 他们如何一起工作? - python - 在具有不同文件名的目录中查找并分隔最大元素
- reactjs - 错误:在 React 中导入图像时找不到模块“./”?
- layout - 在stackview下绘制矩形
- javascript - 如何在 VueJs 3 的渲染函数中将插槽发送到组件
- azure - 具有 Microsoft 身份验证的本地 ASP Core 3.1 MVC 应用程序 - 单租户或多租户
- reactjs - react-select 不会显示默认值