Reputation: 2014
How do I mock out executing a child process in Jest
const execSync = require('child_process').execSync;
//...
expect(execSync)
.toHaveBeenCalledWith('npm install');
But not actually have it run the npm install during the test.
Upvotes: 2
Views: 3869
Reputation: 35513
You can use lib mock with __mocks__
folder that will hold child_process
folder which will be loaded by jest automatically.
Just create a file
// __mocks__/child_process/index.js
module.exports = {
execSync: jest.fn()
};
that will export a mock implementation of child_process
.
Upvotes: 0
Reputation: 21
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.
Upvotes: 2