I have a CommonJS module that contains following exported functions:
// runFunctionalTests.js
const runFunctionalTests = async componentPath => {
const componentPackageJson = getPackageJson(componentPath);
// code
await runTestsLocally(componentName);
};
const getPackageJson = componentPath => {
// code
};
const runTestsLocally = async componentName => {
// code
};
module.exports = {
runFunctionalTests,
getPackageJson,
runTestsLocally,
};
My goal is to write a Jest test to verify that runFunctionalTests call invokes getPackageJson and runTestsLocally functions under the hood.
For now, I've ended with a partial mock attempt that obviously doesn't work: Var 1
const fs = require('fs');
jest.mock('fs');
jest.mock('../runFunctionalTests', () => {
const originalModule = jest.requireActual(
'../runFunctionalTests'
);
return {
__esModule: true,
...originalModule,
getPackageJson: jest.fn(() => 42),
runTestsLocally: jest.fn(() => 43)
};
});
let {
runFunctionalTests,
getPackageJson,
runTestsLocally
} = require('../runFunctionalTests');
describe('runFunctionalTests', () => {
it('should call getPackageJson and runFunctionalTests', async () => {
const packageJsonMock = JSON.stringify({
name: 'TestComponent',
});
fs.readFileSync = jest.fn().mockReturnValue(packageJsonMock);
fs.existsSync = jest.fn().mockReturnValue(true);
getPackageJson.mockReturnValue(true);
runTestsLocally.mockReturnValue(true);
const componentsToTest =
'C:/src/components/test-component';
await runFunctionalTests(componentsToTest);
expect(getPackageJson).toHaveBeenCalled();
expect(runTestsLocally).toHaveBeenCalled();
});
});
Var 2
const fs = require('fs');
jest.mock('fs');
jest.mock('execa');
const sut = require('../runFunctionalTests');
describe('runFunctionalTests', () => {
it('should call getPackageJson and runFunctionalTests', async () => {
const packageJsonMock = JSON.stringify({
name: 'TestComponent',
});
fs.readFileSync = jest.fn().mockReturnValue(packageJsonMock);
fs.existsSync = jest.fn().mockReturnValue(true);
sut.getPackageJson = jest.fn();
sut.runTestsLocally = jest.fn();
const componentsToTest =
'C:/src/components/test-component';
await sut.runFunctionalTests(componentsToTest);
expect(sut.getPackageJson).toHaveBeenCalled();
expect(sut.runTestsLocally).toHaveBeenCalled();
});
});
I've tried to partially mock the *getPackageJson *and *runTestsLocally *functions, but they do not seem to be invoked, the code is running without mocks and both matchers are failing expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
I understand that my mock is not correct, but can't find an example how to properly rewrite it. P.S. fs mocks that are needed for the other methods work fine, the issue is only with getPackageJson and runTestsLocally
Any suggestions?