Stalyon
Stalyon

Reputation: 578

Enzyme - Mocking utils function used in a component

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

Answers (2)

Shishir Anshuman
Shishir Anshuman

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.

Please follow whatever is best for your use case.

Upvotes: 2

Andreas K&#246;berle
Andreas K&#246;berle

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

Related Questions