[英]How to mock a module variable with jest and typscript
我有一个地图定义了一些这样的转换函数
export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) => Promise<any> } = {
[TransformationType.UNZIP]: unzipArchiveAndUploadToS3,
// tslint:disable-next-line: no-empty
[TransformationType.NOOP]: async () => {},
};
后来在同一个模块中,我有一个句柄函数,它根据我提供的一些 seq 调用这些函数。
function handle(funcKeys: TransformationType[]) {
for(const funcKey of funcKey) {
await transformFuncMap[funcKey]();
}
}
当单元测试处理。 我只关心一些函数是按照我提供的顺序调用的。 我不想运行函数实现。
无论如何,是否可以开玩笑地用这样的东西来模拟transformFuncMap
。
export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) => Promise<any> } = {
[TransformationType.UNZIP]:jest.fn(),
// tslint:disable-next-line: no-empty
[TransformationType.NOOP]: jest.fn(),
};
我希望能够做到这一点,而无需在参数中使用某种 Java 风格的依赖注入。
您可以使用jest.fn()
替换transformFuncMap
的原始方法/函数。
index.ts
:
const unzipArchiveAndUploadToS3 = async () => null;
type TransformFunctionArgs = any;
export enum TransformationType {
UNZIP = 'UNZIP',
NOOP = 'NOOP',
}
export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) => Promise<any> } = {
[TransformationType.UNZIP]: unzipArchiveAndUploadToS3,
// tslint:disable-next-line: no-empty
[TransformationType.NOOP]: async () => {},
};
export async function handle(funcKeys: TransformationType[]) {
for (const funcKey of funcKeys) {
const args = {};
await transformFuncMap[funcKey](args);
}
}
index.spec.ts
:
import { handle, transformFuncMap, TransformationType } from './';
describe('59383743', () => {
it('should pass', async () => {
transformFuncMap[TransformationType.UNZIP] = jest.fn();
transformFuncMap[TransformationType.NOOP] = jest.fn();
const funcKeys: TransformationType[] = [TransformationType.NOOP, TransformationType.UNZIP];
await handle(funcKeys);
expect(transformFuncMap[TransformationType.UNZIP]).toBeCalledWith({});
expect(transformFuncMap[TransformationType.NOOP]).toBeCalledWith({});
});
});
带有覆盖率报告的单元测试结果:
PASS src/stackoverflow/59383743/index.spec.ts
59383743
✓ should pass (7ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 84.62 | 100 | 50 | 90 | |
index.ts | 84.62 | 100 | 50 | 90 | 12 |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.626s, estimated 10s
源代码: https : //github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59383743
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.