Search code examples
reactjsunit-testingjestjsenzyme

Mock import/module with Jest in React application


I am working on a React application and I want to test one module, let's call it B, that depends on another module, let's call it A.

The scenario could be something like this:

moduleA.js

export function helperFn() {
  return { prop1: 10, prop2: 20 };
}

moduleB.js

import React from 'react';
import { helperFn } from '../moduleA';

export class CustomComp extends React.Component {
  render() {
    const helperObj = helperFn();
    return (
      <div>{helperObj.prop1}</div>
    );
  }
}

The core libraries to test my components are Jest and Enzyme. My goal here is to test module B, but I want to test it in isolation and so I want to mock the dependency on moduleA.js.

I know one way would be to inject the helperFn as a prop instead of importing it so during the test I can inject a mock function, but there are modules quite big on this app that have a few dependencies each of them.

Researching a bit I found it is posible to mock a dependecy using Jest, but I tried many things with no success. I tried approaches from this question, also from this post and I have no luck. I also read the Manual Mocks and Mock Functions guides from Jest docs, but I think they are pretty confusing.

I could make it work (i.e. I could mock moduleA.js dependency) using the approach on this post, but I had another problem then. It worked just fine to test moduleB.js, but when I went ahead and test moduleA.js, I had to import moduleA.js in moduleA.test.js and I got the mock while I wanted the real module.

So, I need help to understand how I can mock dependency A in moduleB test file.

I hope I was clear if not let me know and I will add the clarifications you might need.

Thanks in advance !


Solution

  • Indeed you can use jest to mock your dependency. There is some configuration you need to set in order to make it work with import. E.g. configuring babel-jest.

    If you already have that configuration then you can mock it like so.

    import React from 'react';
    import { shallow } from 'enzyme';
    import { helperFn } from '../moduleA';
    jest.mock('../moduleA');
    
    describe("CustomComp", () => {
      it("should render component", () => {
        helperFn.mockReturnValueOnce({
          prop1: "dummy"
        });
        const component = shallow(<CustomComp />);
      });
    

    You can see a working example here.