I have
abc.js
const a = (a)=>{
return (b(a) 1)
}
const b = (num)=>{
return(num 1)
}
module.exports = {
a,
b
}
When I do my test for function a, I wanted a mock implementation of function b. but function a, after mocking, still has been using the original implementation instead of my mock.
my test looks something like
abs.test.js
const { a } = require('./abc')
describe('/abc functions',()=>{
beforeEach(()=>{
jest.mock('./abc',()=>(
b = jest.fn.mockReturnValue(5)
))
})
afterEach(()=>{
jest.clearAllMocks()
})
it('uses the b() mock',()=>{
const aResult = a(1)
expect(aResult).toBe(6)
})
})
but I get a result of 2 or whatever the original implementation is. I just wanted my function a to use my mock and it never does. it always goes back to the original implementation.
I tried jest.isolate() to isolate the function im testing. I tried differernt ways of mocking like jest.fn(), jest.spyOn, and the method about jest.requireActual(moduleName)
I tried b = jest.fn().mockImplementation(()=>{})
I am confused as to why function a, even after Isolation, still relies on original implementation of function b...
thank you in advance!
CodePudding user response:
Different approaches to solving the problem. one of it is to "modularize" these functions further by partitioning them into their own modules. more information on this thread: github.com/facebook/jest/issues/936#issuecomment-545080082
CodePudding user response:
You have to remember the rules of lexical scoping and how that ties into the concept of closures. The short answer would be that the reason your test isn't working is because in your module abc.js
your function a()
calls inside its body the function b()
that has been declared in that same module. The environment where the function was defined and NOT the one where it is called is what is called lexical scoping. This combination of the body of a function making use of the bindings where it was defined and the call of that function in the context of that those existing bindings/environment is what's called a closure. So, it doesn't matter if you mock a function b()
and try to use that mock to alter the return value of a()
, a()
will always make use of the original function b()
because that's the rules of lexical scoping dictate