Dav*_*ave 5 unit-testing mocking typescript ts-jest
我正在使用开玩笑和打字稿。我在服务文件中有这个导出的函数......
export async functionprocessData(
data: MyDataI,
): Promise<
...
Run Code Online (Sandbox Code Playgroud)
然后在我通过 npm cli 调用的单独文件 (run-my-process.ts) 中,我有这个
import {processData } from '../services/my.service';
...
processData(data)
.then((result) => {
Run Code Online (Sandbox Code Playgroud)
现在我想从玩笑中模拟“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.');
Run Code Online (Sandbox Code Playgroud)
但是测试因错误而死亡
ERROR [1624482717612] (71310 on localhost): Cannot read property 'then' of undefined
Run Code Online (Sandbox Code Playgroud)
因此,当使用参数调用时,我的函数 processData 似乎以某种方式评估为“未定义”。模拟我的函数以返回 Promise 并让我的 Jest 测试通过的正确方法是什么?
一个更简单的方法可能是:
import * as myService from '../services/my.service';
jest.spyOn(myService, 'processData').mockResolvedValue({ dataInserted: 1 });
Run Code Online (Sandbox Code Playgroud)
使用这个,您可以绕过您尝试使用 jest.mock() 进行的复杂模拟
尝试使用您可能需要适应的任何数据,这里有一篇不错的文章
processData: jest.fn(() => Promise.resolve({ data: {}}))
Run Code Online (Sandbox Code Playgroud)
导出
export default jest.fn(() => Promise.resolve({ data: {} }));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
281 次 |
最近记录: |