I'm using Jest to test some Javascript. In a file, called 'function.js' I have two functions like so:
functions.js
const firstFunc = () => {
const x = secondFunc()
return x
}
const secondFunc = () => {
return '5'
}
module.exports = {
firstFunc,
secondFunc
}
In my Jest test file I have:
const functions = require('./functions.js')
test('test if secondFunc is called', () => {
const mockFunction = jest.fn()
functions.secondFunc = mockFunction;
functions.firstFunc()
expect(mockFunction).toHaveBeenCalled()
})
I've actually tried many different variations of things like this. I'm unable to get jest.fn() to work I want it to. Overall I'm wanting to be able to see information about secondFunc, such as how many times it was called, what parameters with, etc, but I have to actually call firstFunc. Can anyone help me as I can't seem to figure this out.
You need to do some refactoring. Keep the same reference for secondFunc.
Then you can replace it with a mocked object.
functions.js:
const firstFunc = () => {
const x = exports.secondFunc();
return x;
};
const secondFunc = () => {
return '5';
};
exports.firstFunc = firstFunc;
exports.secondFunc = secondFunc;
unit test result:
PASS stackoverflow/62583841/functions.test.js (12.17s)
✓ test if secondFunc is called (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.779s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With