【发布时间】:2021-06-24 02:26:36
【问题描述】:
我正在使用 jest 和 Typescript。我在服务文件中有这个导出的函数...
export async functionprocessData(
data: MyDataI,
): Promise<
...
然后在我通过 npm cli 调用的单独文件 (run-my-process.ts) 中,我有这个
import {processData } from '../services/my.service';
...
processData(data)
.then((result) => {
现在我想从 jest 中模拟“processData”函数,所以我尝试了这个
jest.mock('../services/my.service', () => {
// The mock returned only mocks the generateServerSeed method.
const actual = jest.requireActual('../services/my.service');
return {
...actual,
processData: jest.fn().mockReturnValue(Promise.resolve({
dataInserted: 1,
}))
}
});
...
describe('calls the job', function () {
it('invokes the function', async () => {
...
jest.spyOn(process, 'exit').mockImplementationOnce(() => {
throw new Error('process.exit() was called.');
});
expect(() => {
require('./run-my-process');
}).toThrow('process.exit() was called.');
但测试因错误而终止
ERROR [1624482717612] (71310 on localhost): Cannot read property 'then' of undefined
因此,当使用参数调用时,我的函数 processData 似乎以某种方式评估为“未定义”。模拟我的函数以返回 Promise 并让我的 Jest 测试通过的正确方法是什么?
【问题讨论】:
-
我注意到您将
mockReturnValue()用于processData。您可能想尝试mockResolvedValue(),因为它看起来像是在进行异步测试。 -
嗨,戴夫,你试过我的code snippet。如果您需要更多,我可以添加更深入的示例
标签: typescript unit-testing mocking ts-jest