Jest - 测试使用 react-router 的组件

IT技术 reactjs react-router jestjs
2021-05-24 02:28:41

我正在测试一个组件,该组件呈现具有以下 contextTypes 的子组件:

Component.contextTypes = {router: PropTypes.object.isRequired}

我对开玩笑完全陌生,但是来自摩卡咖啡/酶我从来没有遇到过这个问题。

我的第一个测试看起来像这样,我真的只是想看看它是如何工作的:

it('should exist', () => {
    wrapper = renderer.create(<Companies/>);
    let tree = wrapper.toJSON();
    expect(tree).toMatchScreenshot();
});

当我运行测试时,我收到以下错误:

Failed context type: The context `router` is marked as required in `ChildComponent`, but its value is `undefined`.

是否有解决此问题的方法,或者只是我缺少的文档中的某些内容?提前致谢!

解决方案:对于遇到相同问题的任何人,我在 beforeEach() 中使用了以下内容:

    MyComponent.contextTypes = {
        router: function () {
            return {
                transitionTo: jest.genMockFunction()
            };
        }
    };
1个回答

<Link>在某些组件中使用时遇到了类似的问题,并遇到了与上述相同的错误。就我而言,我使用的是 react-router 4.1.1 并且上面的解决方案不起作用。

我在上下文中添加了对象和函数,但我希望有人为此提供更好的解决方案。

describe('SomeComponent', ()=>{

  it('renders component', ()=>{
    const wrapper = mount(
      <SomeComponent />,
      {
        context: {
          router: {
            history: {
              push: ()=>{},
              replace: ()=>{},
              createHref: ()=>{},
            }
          }
        },
        childContextTypes: {
          router: PropTypes.object.isRequired,
        }
      }
    )
    expect(wrapper.text()).toContain('some component text')
  })

})

我正在使用酶mount