我正在编写一个cli工具,并试图在Jest中为其编写测试。我有一些调用git的函数,但是我需要模拟这些调用的返回值,否则它们将不一致。
我用来调出外壳的代码如下所示。
import { exec } from "child_process";
function execute(command) {
return new Promise((resolve, reject) => {
exec(command, resolve);
});
}
export const getGitDiff = function () {
return execute("git diff")
};
如何在Jest中为此编写测试?
我试过的是
import { getGitDiff } from './getGitDiff';
describe('get git diff', () => {
it('should send "git diff" to stdin', () => {
const spy = jest.spyOn(process.stdin, 'write');
return getGitDiff().then(() => {
expect(spy).toHaveBeenCalled();
})
});
});
最佳答案
我最终创建了一个名为child_process.js
的新文件,并在Jest中使用genMockFromModule
功能对整个模块进行存根,并重新实现了某些类似这样的功能
const child_process = jest.genMockFromModule('child_process');
const mockOutput = {}
const exec = jest.fn().mockImplementation((command, resolve) => {
resolve(mockOutput[command]);
})
const __setResponse = (command, string) => {
mockOutput[command] = string;
}
child_process.exec = exec
child_process.__setResponse = __setResponse;
module.exports = child_process;
我有一个像
const child_process = jest.genMockFromModule('child_process');
const mockOutput = {}
const exec = jest.fn().mockImplementation((command, resolve) => {
resolve(mockOutput[command]);
})
const __setResponse = (command, string) => {
mockOutput[command] = string;
}
child_process.exec = exec
child_process.__setResponse = __setResponse;
module.exports = child_process;