In case you're interested, I solved this already using the first solution provided. I was missing babel from jest, I was using the experimental es6 settings found in jest documentation stating I should remove the transformation, add test node --experimental-vm-modules node_modules/jest/bin/jest.js, etc. Not really sure what is that for, I thought it was for this very thing but apparently not.
I've read many posts here and tried many solutions but nothing seems to work for me, how can I test in Jest that the calling
function is being called inside init
?
Here's what I have:
calling.js
const calling = () => {
return 'calling';
};
export default calling;
init.js
import calling from './calling';
export const init = () => {
calling();
};
test.spec.js
import { jest } from '@jest/globals';
import init from './init.js';
import calling from './calling.js';
test('init calls calling', () => {
// what to do here?
});
package.json
{
"name": "testing",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
},
"type": "module",
"jest": {
"transform": {},
"roots": [
"<rootDir>"
],
"modulePaths": [
"<rootDir>"
],
"moduleDirectories": [
"node_modules"
]
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/jest": "^28.1.8",
"jest": "^28.1.3"
}
}
};
It kind of work now based on the solution provided above BUT! I have to do a more complicated setup in order to work and I can't figure out why. Also, I had to do name exports because it doesn't work with default export and I can't figure out how to do it either.
import { jest } from '@jest/globals';
const mock = jest.fn();
jest.unstable_mockModule('./calling.js', () => ({
calling: mock,
}));
const { calling } = await import('./calling.js');
const { init } = await import('./init.js');
test('test', async () => {
init();
expect(calling).toHaveBeenCalled();
});
CodePudding user response:
In this case, you can simply use the Jest autoMocking function and verify whether it actually been called
// test.spec.js
import { init } from './init';
import calling from './calling';
jest.mock('./calling');
test('init calls fn calling', () => {
init();
expect(calling).toHaveBeenCalled();
});
I assume it did not work out for you because you have a mistake in importing
import init from './init.js'; // not default export
// should be
import {init} from './init.js';