Reputation: 1274
My question is about how to mock jest function importing from another file as default.
What I want to test is that component using function to enabled Feature (Features.js
)
I mocked this function using jest.fn() and tried to change value using mockReturnValueOnce
It looks like below.
mocks/features.js
export default function isFeatureEnabled (featureName) {
return true // want to test both true/false cases
}
test.spec.js
jest.mock('__mocks__/features.js', () => ({
isFeatureEnabled: jest.fn()
}))
describe('isFeatureEnabled', () => {
it('isFeatureEnabled=[true]', () => {
isFeatureEnabled.mockReturnValueOnce(true)
// some tests
})
it('isFeatureEnabled=[false]', () => {
isFeatureEnabled.mockReturnValueOnce(false)
// some tests
})
})
When I run the test, I got an error says mockReturnValueOnce is not a function
. This stackoverflow question inspired me to implement in this way, however still I cannot figure it out how to make it working.
Upvotes: 2
Views: 17226
Reputation: 45780
You're close.
Here is a simple working example that demonstrates what you are trying to do:
features.js
export default function isFeatureEnabled (featureName) {
// this is the actual implementation...
return true // ...but for the example just return true
}
__mock__/features.js
export default jest.fn(() => true); // default export is mock that returns true
code.js
import isFeatureEnabled from './features';
export const funcToTest = () => isFeatureEnabled() ? 'enabled' : 'not enabled';
code.test.js
import { funcToTest } from './code';
import isFeatureEnabled from './features';
jest.mock('./features'); // use the manual mock
describe('funcToTest', () => {
it('isFeatureEnabled=[true]', () => {
isFeatureEnabled.mockReturnValueOnce(true);
expect(funcToTest()).toBe('enabled'); // Success!
})
it('isFeatureEnabled=[false]', () => {
isFeatureEnabled.mockReturnValueOnce(false);
expect(funcToTest()).toBe('not enabled'); // Success!
})
})
Upvotes: 4
Reputation: 906
I think you should test result of you function. Import isFeatureEnabled and test what it returns. I don't get it why you use mock.
import isFeatureEnabled from './isFeatureEnabled'
describe('Testing features', () => {
it('isFeatureEnabled should return true if "add" feature is enabled', () => {
const feature = 'add'
const result = isFeatureEnabled(feature)
expect(result).toEqual(true)
})
});
Upvotes: 1