2017-05-03 100 views
9

我使用jest來測試來自react-router v4的<Link>組件。使用Jest測試來自react-router v4的鏈接

我收到一條警告,要求<Link />需要來自反應路由器<Router />組件的上下文。

如何在我的測試中模擬或提供路由器上下文? (基本上,我怎麼解決這個警告?)

Link.test.js

import React from 'react'; 
import renderer from 'react-test-renderer'; 
import { Link } from 'react-router-dom'; 

test('Link matches snapshot',() => { 
    const component = renderer.create(
    <Link to="#" /> 
); 

    let tree = component.toJSON(); 
    expect(tree).toMatchSnapshot(); 
}); 

當測試運行的警告:

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

回答

12

你可以用你的組件在與StaticRouter的測試中獲取路由器上下文到您的組件中:

import React from 'react'; 
import renderer from 'react-test-renderer'; 
import { Link } from 'react-router-dom'; 
import { StaticRouter } from 'react-router' 

test('Link matches snapshot',() => { 
    const component = renderer.create(
    <StaticRouter location="someLocation" context={context}> 
     <Link to="#" /> 
    </StaticRouter> 
); 

    let tree = component.toJSON(); 
    expect(tree).toMatchSnapshot(); 
}); 

看一看的反應路由器docs about testing

0

我有同樣的問題,並使用StaticRouter仍然需要這需要更多的配置,有它在我的測試中可用的context,所以我結束了使用其非常合作的MemoryRouter好,沒有任何問題。

import React from 'react'; 
import renderer from 'react-test-renderer'; 
import { MemoryRouter } from 'react-router-dom'; 

// SampleComponent imports Link internally 
import SampleComponent from '../SampleComponent'; 

describe('SampleComponent',() => { 
    test('should render',() => { 
    const component = renderer 
     .create(
     <MemoryRouter> 
      <SampleComponent /> 
     </MemoryRouter> 
    ) 
     .toJSON(); 

    expect(component).toMatchSnapshot(); 
    }); 
});