I'm currently having a problem with mocking a function inside another lib.
In our team, we have a project (npm lib, let's call it component-lib) with some components and functions that are being used by our React main app. We expose the functions and components in a single JS file. (index.js) like this:
import { isFeatureEnabled } from './modules/features'
import mockComponent from './components/mockComponent'
export {
isFeatureEnabled,
mockComponent
}
I'm trying to mock the return value of one of the functions inside this component-lib that is being used by the main react app, my unit test goes like this:
PS: I'm using Jest and React Testing Library
describe('unit test', () => {
jest.mock('component-lib', () => ({
...jest.requireActual('component-lib'),
isFeatureEnabled: jest.fn().mockReturnValue(false)
}))
it('Should send data', () => {
render(<Main />)
[... i do some stuff here and trigger the isFeatureEnabled function ...]
})
})
and the code I use it:
function onSubmitPassword (data) {
console.log('is this feature enabled? ', isFeatureEnabled('feature')) // logs as true
if (isFeatureEnabled('feature') {
...do this // this is executed
} else {
do that
}
}
The thing is that when I do a console.log to see the value of isFeatureEnabled, it's returning true instead of false, ignoring the mock.
Do you guys have any idea why the mock is not working in this case?
I already tried importing the lib as:
import * as components from 'component-lib'
jest.mock('component-lib', () => ({
...jest.requireActual('component-lib'),
isFeatureEnabled: jest.fn()
}))
it('Should send data', () => {
isFeatureEnabled.mockReturnValue(false)
render(<Main />)
[... i do some stuff here and trigger the isFeatureEnabled function ...]
})
and it returns an error saying the function only has a getter