我有一个定义一些像这样的转换函数的 map
export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) => Promise<any> } = {
[TransformationType.UNZIP]: unzipArchiveAndUploadToS3,
// tslint:disable-next-line: no-empty
[TransformationType.NOOP]: async () => {},
};
后来在同一个模块中,我有一个句柄函数,它根据我提供的某些序列调用这些函数。
function handle(funcKeys: TransformationType[]) {
for(const funcKey of funcKey) {
await transformFuncMap[funcKey]();
}
}
当单元测试处理时。我所关心的是按照我提供的顺序调用某些函数。我不想运行函数实现。
无论如何,是否有 Jest 可以用类似这样的东西来模拟 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 风格的依赖注入(inject)。
最佳答案
您可以使用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
关于javascript - 如何使用 Jest 和 typescript 模拟模块变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59383743/