I have a index.js file in nodejs as below,
const child1 = async (arg)=> {
//axios.post(<url>, {input: arg})
}
I have index.js file as below code
const child1 = async (arg) {
//const resp = test; //axios.post(<url>, {input: arg})
return resp;
}
const parent = async () {
const arg = 'custom_id'
const c1 = await child1(arg)
return c1
}
module.exports = {child1, parent}
I want to write unit test case in index.test.js as below,
const {child1, parent} = require('./index')
describe('parent', () => {
it('calls child1 with the correct argument', async () => {
const mockupResponse = 'test'
child1.mockResolvedValue(mockupResponse);
await parent();
expect(child1).toHaveBeenCalledWith('custom_id');
});
});
Output:
Expected:custom_id
Number of calls: 0
I also tried with other way - manual mock
jest.mock('./index', ()=>{
const orginalModule = jest.requireActual('./../index')
return {
...orginalModule,
child1: jest.fn()
}
})
const {child1, parent} = require('./index')
describe('parent', () => {
it('calls child1 with the correct argument', async () => {
child1.mockResovedValue('test')
await parent();
expect(child1).toHaveBeenCalledWith('custom_id');
});
});
Output:
Expected:custom_id
Number of calls: 0
In debugging, for test command ‘npm run test’, child1 function has invoked from parent() function but it looks like mocking of child function is not took place. Please suggest.
New contributor
rohan mishra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.