简体   繁体   English

在 Jest 中模拟 execSync

[英]Mocking execSync in Jest

How do I mock out executing a child process in Jest我如何模拟在 Jest 中执行子进程

const execSync = require('child_process').execSync;
//...
expect(execSync)
  .toHaveBeenCalledWith('npm install');

But not actually have it run the npm install during the test.但实际上并没有让它在测试期间运行 npm install。

Can just do something like the following:可以执行以下操作:

jest.mock("child_process", () => {
  return {
    execSync: () => "This is a test message"
  };
});

Where the return value can be a number, string, object or whatever.返回值可以是数字、字符串、对象或其他任何内容。 It just allows you to override the actual implementation of execsync.它只允许您覆盖 execsync 的实际实现。

You can use lib mock with __mocks__ folder that will hold child_process folder which will be loaded by jest automatically.您可以将lib mock__mocks__文件夹一起使用, __mocks__文件夹将包含将由 jest 自动加载的child_process文件夹。

Just create a file只需创建一个文件

// __mocks__/child_process/index.js

module.exports = {
  execSync: jest.fn()
};

that will export a mock implementation of child_process .这将导出child_process的模拟实现。

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

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