Using Jest to mock a React component with props

前端 未结 3 1517
清歌不尽
清歌不尽 2020-12-29 04:45

I have a React component which contains some other components that depend on access to a Redux store etc., which cause issues when doing a full Enzyme mount. Let\'s say a st

相关标签:
3条回答
  • 2020-12-29 05:23

    I've learned a little more since I asked this question. Here's an alternative (better?) way of dealing with mocking components that need to be passed props: using module mock files.

    First create a file with the same name as the component to mock in a __mocks__ folder under the component's folder e.g.

    .
    |- /ComponentToMock.js
    └- /__mocks__/ComponentToMock.js <-- create this folder/file!
    

    Note: It seems as of the time of writing, the folder must be called __mocks__ (you will need to create __mocks__ in each folder you need to mock components for. If the underscores upset you, just pretend they aren't there ;) )

    Next, in this mock file, you can write the file as you wish, e.g.

    // This code would live in ./__mocks__/ComponentToMock.js
    import React from 'react';
    const ComponentToMock = ({ testProp }) => <div>A mock with '{testProp}' passed!</div>;
    export default ComponentToMock;
    

    Then in the test file, change the Jest mock statement to: jest.mock('./ComponentToMock');

    When Jest encounters a .mock() without the second function parameter, it automatically looks for a __mocks__ folder. However, even though the mock statement gets hoisted in the component being tested, this doesn't affect the imports of the mock itself - hence why it's able to import and compile a React component!

    This seems to work well for mocked components that need to be passed props, and would otherwise produce prop warnings if a nulled function was returned (but which is perfectly acceptable to continue using if the component does not receive props). I hope this helps some people out there.

    0 讨论(0)
  • 2020-12-29 05:26

    There's a note at the bottom of the docs for jest.mock() for preventing the hoisting behavior:

    Note: When using babel-jest, calls to mock will automatically be hoisted to the top of the code block. Use doMock if you want to explicitly avoid this behavior.

    Then you can do as you described: return a function that is a stub of the component you don't need to test.

    jest.doMock('./ComponentToMock', () => {
      const ComponentToMock = () => <div />;
      return ComponentToMock;
    });
    
    const ComponentToTest = require('./ComponentToTest').default;
    

    It's helpful to name the stub component since it gets rendered in snapshots.

    0 讨论(0)
  • 2020-12-29 05:27

    In my case, I was unable to make the mock work.

    An it turned out to be case-sensitivity issue:

    Module Filename: Autosuggest.js

    How i was mocking it: jest.mock('./AutoSuggest', ...); <-- wrong cases

    0 讨论(0)
提交回复
热议问题