1
votes

I am attempting to test a React Component with Jest and Enzyme, but my test fails to run because it seems to be having trouble with a specific node module. The module that is breaking the test is actually imported from a component that sits inside the one I am trying to test.

Here is the hierarchy:

  • Insights
    • BuildOnScrollHelper (this is where the node module is imported).

When I run this test:

import React from 'react';
import { shallow } from 'enzyme';
import { View } from 'react-native';
import { Insights } from '../../containers/Insights';
import insightsMockData from '../../mocks/data/insights';

describe('Insights Container', () => {
  let cmp;

  beforeEach(() => {
    cmp = shallow(
      <Insights
        {...insightsMockData}
        loadReports={jest.fn()}
        fetchGraph={jest.fn()}
      />,
    );
  });

  it('does stuff', () => {
    console.log(cmp.debug());
  });
});

I get this error from Jest in the console:

enter image description here

If I go into my Insights React Component and comment out the BuildOnScrollHelper component(and its import statement) the test runs perfectly fine.

I had two ideas:

  1. I don't even need to mock the node module, perhaps I could just mock BuildOnScrollHelper itself? For this test I don't care about BuildOnScrollHelpers functionality at all.
  2. I will have to mock the node module.

Does anyone know how I would go about this in a manner that is considered good practice? I have spent a few hours trying to hunt down solutions to this, but still can't get my test to work.

Ideally I would like an answer that provides some code examples, and not just a link to a piece of documentation.

1

1 Answers

0
votes

Check this link out.

Mocking Node modules

If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the mocks directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.mock('module_name').

Scoped modules can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called @scope/project-name, create a file at mocks/@scope/project-name.js, creating the @scope/ directory accordingly.