【发布时间】:2021-03-01 20:20:12
【问题描述】:
我正在尝试从 fs 模块(fs.promises)模拟 copyFile 和 stat 方法。但是没有调用模拟函数,而是调用了原始函数,尽管测试用例通过了。
测试功能代码为:
jest.doMock('fs', () => ({
promises: {
copyFile: (src = 'source', dest = 'destination') =>
jest.fn().mockImplementation(async () => {
console.log('Inside the mock function in copyFile, please get executed, got frustrated', src, dest);
return Promise.resolve(false);
}),
stat: () =>
jest.fn().mockImplementation(async () => {
console.log('Inside the mock function in stat method, please get executed, got frustrated');
return Promise.resolve(false); // Probably wrong datatype
}),
},
}));
describe('Testing implementation', () => {
const sample = new MainFunction()
test('Testing', async () => {
expect(sample.demo()).toEqual(Promise.resolve(true));
});
});
需要测试的实际代码:
import * as fs from 'fs';
export class MainFunction {
async demo(): Promise<any> {
const fileName = 'C:/Users/Desktop/testing-file-dir/';
const fileName1 = '/destination/'
let filefound = (await fs.promises.stat(fileName)).isFile();
await fs.promises.copyFile(fileName,fileName1);
console.log(filefound, 'inside actual code');
return Promise.resolve(true);
}
}
有人可以帮忙解决我哪里出错了吗?我曾想过使用 jest.mock,但它也给出了错误,所以我点击了这个链接 https://github.com/facebook/jest/issues/2567,它建议尝试 doMock。如果有人知道更好的方法来处理这个模拟函数,那就太好了。
谢谢!
【问题讨论】:
标签: javascript node.js typescript jestjs mocking