Using Jest to mock a React component with props

前端 未结 3 1516
清歌不尽
清歌不尽 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: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 = () => 
    ; return ComponentToMock; }); const ComponentToTest = require('./ComponentToTest').default;

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

提交回复
热议问题