【问题标题】:Mock shell command output in JestJest 中的 Mock shell 命令输出
【发布时间】:2020-09-10 01:07:05
【问题描述】:

我正在编写一个 cli 工具,并尝试在 Jest 中为它编写测试。我有一些调用 git 的函数,但我需要模拟这些调用的返回,否则它们将不一致。

我用来调用 shell 的代码如下所示。

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();
    })
  });
});

【问题讨论】:

    标签: javascript node.js testing jestjs


    【解决方案1】:

    我最终创建了一个名为 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;
    

    【讨论】:

    • 嗨,我很好奇你在这里做什么,但看起来你只是将同一个源粘贴了两次。
    猜你喜欢
    • 1970-01-01
    • 2016-04-21
    • 2015-02-11
    • 2021-04-24
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多