如何用玩笑和打字稿模拟模块变量

时间:2019-12-17 23:54:35

标签: javascript typescript jestjs

我有一张地图,定义了一些这样的转换函数

export const transformFuncMap: { [key: string]: (args: TransformFunctionArgs) => Promise<any> } = {
    [TransformationType.UNZIP]: unzipArchiveAndUploadToS3,
    // tslint:disable-next-line: no-empty
    [TransformationType.NOOP]: async () => {},
};

稍后在同一模块中,我有一个handle函数,该函数根据我提供的一些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样式依赖项注入。

1 个答案:

答案 0 :(得分:1)

您可以使用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