Dog
Dog

Reputation: 2906

Globally mock a function in Jest/Enzyme in React

Oftentimes I have functions that are imported into a React component that I want to test using jest/enzyme.

Normally, I can access a function defined in a component through wrapper.instance().functionName and then test if the function has been called. Similarly, I can pass a mock function in as props when mounting a component in a test, and then checking to see if that component has been called. However, I have no methods of testing functions that are imported into components (not defined internally or as props).

Is there a way to use jest/enzyme to define a global mock function that will be used in a component test that will override the implementation of function of the same name that has been imported into the component I'm testing?

Upvotes: 3

Views: 5996

Answers (1)

Brian Adams
Brian Adams

Reputation: 45800

Yes, that is possible.

There are many different ways to mock modules or individual functions within modules.


Here is one example:

lib.js

export const importedFunc = () => 'original';

code.js

import * as React from 'react';
import { importedFunc } from './lib';

export class SimpleComponent extends React.Component {
  render() {
    return (<div>{ importedFunc() }</div>);
  }
}

code.test.js

import * as React from 'react';
import { shallow } from 'enzyme';
import * as lib from './lib';
import { SimpleComponent } from './code';

test('SimpleComponent', () => {
  const spy = jest.spyOn(lib, 'importedFunc');
  spy.mockReturnValue('mocked');
  const wrapper = shallow(<SimpleComponent />);
  expect(wrapper.html()).toBe('<div>mocked</div>');  // Success!
  expect(spy).toHaveBeenCalled();  // Success!
});

jest.spyOn wraps a function in a spy, and you can change how the spy behaves with any of its methods such as mockReturnValue, mockImplementation, etc.

jest.mock lets you mock an entire module.

Manual mocks allow you to create module mocks that can be used across tests.

Upvotes: 5

Related Questions