3
votes

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?

1
If you feel the need to test that function, test it individually, or turn it into a prop on your components.Emile Bergeron

1 Answers

4
votes

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.