使用 Jest 测试来自 react-router v4 的链接 [英] Using Jest to test a Link from react-router v4
本文介绍了使用 Jest 测试来自 react-router v4 的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 jest
来测试带有来自 react-router v4 的 的组件.
I'm using jest
to test a component with a <Link>
from react-router v4.
我收到一个警告,提示 需要来自 react-router
组件的上下文.
I get a warning that <Link />
requires the context from a react-router <Router />
component.
如何在测试中模拟或提供路由器上下文?(基本上我该如何解决这个警告?)
How can I mock or provide a router context in my test? (Basically how do I resolve this warning?)
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`.
推荐答案
您可以在测试中使用 StaticRouter 包装您的组件,以将路由器上下文放入您的组件中:
You can wrap your component in the test with the StaticRouter to get the router context into your component:
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();
});
查看 react 路由器 有关测试的文档
Have a look at the react router docs about testing
这篇关于使用 Jest 测试来自 react-router v4 的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文