简体   繁体   English

在 Jest 中模拟 shell 命令输出

[英]Mock shell command output in Jest

I'm writing a cli tool and I'm trying to write tests for it in Jest.我正在编写一个 cli 工具,我正在尝试在 Jest 中为它编写测试。 I have some functions that call out to git, but I need to mock the returns from those calls or they aren't going to be consistent.我有一些调用 git 的函数,但我需要模拟这些调用的返回值,否则它们将不一致。

The code I'm using to call out to the shell looks like this.我用来调用 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")
};

How can I write a test for that in Jest?我如何在 Jest 中为此编写测试?

What I tried was我试过的是

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

I ended up creating a new file called child_process.js and using the genMockFromModule functionality in Jest to stub the whole module and reimplemented some of the functions like this我最终创建了一个名为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;

and I have a test like我有一个像

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM