Reputation: 578
In my React app, I want to test a component which call a utils function from another file. In a particular case, I do want to mock this result. How can I do this using Enzyme and Jest?
This is the code:
// MyComponent
import React from 'react';
import { getCalculatedValue } from '../utils';
export class MyComponent extends React.Component {
constructor(props) {
const calculatedValue = getCalculatedValue();
// ...
}
// ...
}
And the test:
// MyComponent test
describe('MyComponent ', () => {
it('should be...', () => {
const myComponent= shallow(
<MyComponent />
)
expect(myComponent.find('....').length).toBeDefined()
})
})
The method I want to mock is getCalculatedValue
.
Upvotes: 1
Views: 2490
Reputation: 1125
You could simply do the following in your test file:
getCalculatedValue = jest.fn().mockReturnValue(YOUR_RETURN_VALUE);
Now when you create a component tree using the shallow
, the getCalculatedValue
will always return YOUR_RETURN_VALUE.
You could also the the mockImplementation.
If you have multiple functions in the utils.js, and you want to mock them all, I would recommend following this doc: https://facebook.github.io/jest/docs/en/manual-mocks.html#mocking-user-modules. And just calling jest.mock('path/to/utils')
Please follow whatever is best for your use case.
Upvotes: 2
Reputation: 110892
You can use jest.mock
to mock the module like this, note that the path '../utils'
is relative to the test file :
jest.mock('../utils', ()=>({getCalculatedValue: ()=> 'someValue'}))
If you need to mock the module with different return values for getCalculatedValue
you need to mock the module with jest.fn(), import it into your test and change the implementation in your tests:
jest.mock('../utils', ()=>({getCalculatedValue: jest.fn()}))
import { getCalculatedValue } from '../utils';
it('test1',()=>{
getCalculatedValue. mockReturnValue('someValue')
})
it('test2',()=>{
getCalculatedValue. mockReturnValue('anotherValue')
})
Upvotes: 4