【问题标题】:Jest mock always gives undefined (typescript + ts-jest)Jest mock 总是给出 undefined (typescript + ts-jest)
【发布时间】:2019-12-12 22:32:48
【问题描述】:

我似乎无法让 mock 正常工作。

一点上下文:

    "jest": "^24.8.0",
    "ts-jest": "^24.0.2",
    "typescript": "^3.5.3"

  • storage.ts 包含一个方法getOsTmpDir

  • moduleA.ts 正在消耗 storage.ts

  • moduleA.spec.ts 中:

jest.mock('./storage', () => ({
    getOsTmpDir: jest.fn().mockImplementation(() => '/tmp'),
}));

打印(在console.log(getOsTmpDir());给出undefined

我尝试过的其他事情:

  • getOsTmpDir: jest.fn(() => '/tmp')
  • getOsTmpDir: jest.fn().mockReturnValue('/tmp')

但似乎没有任何帮助。我错过了什么?


编辑:我找到了问题。我没有注意到所有模拟在每次测试之前都会重置,因为我已经在文件顶部定义了模拟(一次) ,模拟在运行任何测试之前就被终止了

beforeEach(async () => { jest.resetAllMocks(); <---- .... }

【问题讨论】:

  • 考虑将您的答案发布为答案而不是编辑 :)

标签: typescript mocking jestjs ts-jest


【解决方案1】:

您如何导出/导入该方法?这是模拟导出函数时的样子:

定义“真实”函数:

~fileA.ts
...

export function what() {
  console.log('A');
}
...

测试:

~test.ts
...

import { what } from './fileA';

jest.mock('./fileA', () => ({
    what: jest.fn().mockImplementation(() => console.log('B')),
}));

describe('mocks', () => {
  it('should work', () => {
    what();
  });
});
$ jest test.ts

...
console.log test.ts:9
    B

您应该会看到该测试调用了 what 的模拟实现并记录了一个 B。

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 2021-06-01
    • 2018-09-10
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 2020-03-12
    • 2018-12-11
    • 2018-12-02
    相关资源
    最近更新 更多