2017-02-22 53 views
1

我測試呈現具有以下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() 
      }; 
     } 
    }; 
+0

它使用哪個版本的react-router? – paqash

+0

@paqash版本2.4.1 – Jake

回答

2

我有一個類似的問題,我在一些組件使用<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