Jest - testing a component that uses react-router

2019-07-15 05:28发布

问题:

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!

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

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

回答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')
  })

})

I'm using enzyme for mount.