我正在使用jest来测试一个带有< Link>的组件.来自react-router v4.
我收到一条警告< Link />需要来自react-router< 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: @R_404_159@ context type: The context `router` is marked as required in `Link`,but its value is `undefined`.
您可以使用StaticRouter将组件包装在测试中,以将路由器上下文放入组件中:
原文链接:https://www.f2er.com/react/301259.htmlimport 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