开玩笑-测试使用react-router的组件 [英] Jest - testing a component that uses react-router

查看:310
本文介绍了开玩笑-测试使用react-router的组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am testing a component that renders a child component that has the following contextTypes:

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

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

I am completely new to jest, but coming from mocha/enzyme I've never ran into this problem.

我的第一个测试是这样的,我真的只是在弄乱它,看看它是如何工作的:

My first test looks like this, and I'm really just messing around with it to see how it works:

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

运行测试时,出现以下错误:

When I run the test I get the following error:

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

是否可以解决此问题,或者只是我缺少的文档中的某些内容?预先感谢!

Is there a work around for this, or just something in the docs I'm missing? Thanks in advance!

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

SOLUTION: For anyone that runs into the same issue, I used the following in a beforeEach():

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

推荐答案

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

I had a similar issue when I was using <Link> in some component, and faced same error as above. In my case I was using react-router 4.1.1 and solution above didn't work.

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

I added object and functions into context, but I hope someone give me better solution for this.

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使用酶.

这篇关于开玩笑-测试使用react-router的组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆