Sometimes, we want to use actual function in a module when module is mocked in Jest.
In this article, we’ll look at how to use actual function in a module when module is mocked in Jest.
How to use actual function in a module when module is mocked in Jest?
To use actual function in a module when module is mocked in Jest, we can use the jest.requireActual
method.
For instance, we write:
import {
otherFn
} from './myModule.js'
jest.mock('./myModule.js', () => ({
...(jest.requireActual('./myModule.js')),
otherFn: jest.fn()
}))
describe('test category', () => {
it('tests something about otherFn', () => {
otherFn.mockReturnValue('foo')
expect(otherFn()).toBe('foo')
})
})
to mock myModule
with jest.mock
but use the actual members in myModule
to with jest.requireActual
.
Then we mock otherFn
in the same module by setting otherFn
to jest.fn
.
And then in our test, we call otherFn.mocklReturnValue
to mock otherFn
‘s return value.
Finally, we check otherFn
‘s return value with toBe
.
Conclusion
To use actual function in a module when module is mocked in Jest, we can use the jest.requireActual
method.