gpt4 book ai didi

react-router - 使用 Jest 测试来自 React-router v4 的链接

转载 作者:行者123 更新时间:2023-12-03 13:54:09 25 4
gpt4 key购买 nike

我正在使用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: Failed context type: The context `router` is marked 
as required in `Link`, but its value is `undefined`.

最佳答案

您可以使用 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();
});

看看 React 路由器 docs about testing

关于react-router - 使用 Jest 测试来自 React-router v4 的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com