使用Jest测试来自React-Router v4的链接 [英] Using Jest to test a Link from react-router v4

查看:430
本文介绍了使用Jest测试来自React-Router v4的链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jest来测试来自react-router v4中带有<Link>的组件.

I'm using jest to test a component with a <Link> from react-router v4.

我得到一个警告,指出<Link />需要来自react-router <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();
});

看看反应路由器有关测试的文档

这篇关于使用Jest测试来自React-Router v4的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆