Mock a function called by child process in Jest

340 Views Asked by At

I have been writing unit tests for a grunt task and want to mock "request" that the grunt task encounters during its execution. I am using "exec" to call the grunt task in the child process of a nodejs jest test.

task.js

const request = require('request');
//grunt task registration  and other stuff
//...

request(url,function(error,response,body){
            //logic
            });

task.spec.js

const exec = require('child_process').exec
const request = require)'request')
jest.mock('request')

describe('UT for something',()=>{
    it('should pass',async ()=>{

        request.mockImplentation((url,cb)=>{
            cb(undefined,undefined,'mocked response');
            });

        const execChild = () => {
                return new Promise((resolve,reject)=>{
                    exec('grunt task',(error,stdout,stderr)=>{
                        if(error) reject(error);
                        resolve(stdout ? stdout :stderr);
                            })
                    })
            }

        await execChild();
        //rest of the code
})
})

The problem is that when i run the test case the mocked implementation of the request module is not used and the original call is being made. I have a hunch that maybe the request module is being mocked only for the main process and when child process is spawned it uses the original request module and that it is not receiving the mocked value of the module. Any idea on how i can mock the request module for the child process as well ?

i ran this test in debug mode and the other tests where i have successfully mocked the request module and the difference was that in other tests when i look the request function i could it is mocked as it has a property in it like "isMocked:true" which is missing when i do the same for the problematic test

0

There are 0 best solutions below