gpt4 book ai didi

reactjs - 如何模拟 react 路由器上下文

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

我有相当简单的 react 组件(链接包装器,如果路由处于事件状态,则会添加“事件”类):

import React, { PropTypes } from 'react';
import { Link } from 'react-router';

const NavLink = (props, context) => {
const isActive = context.router.isActive(props.to, true);
const activeClass = isActive ? 'active' : '';

return (
<li className={activeClass}>
<Link {...props}>{props.children}</Link>
</li>
);
}

NavLink.contextTypes = {
router: PropTypes.object,
};

NavLink.propTypes = {
children: PropTypes.node,
to: PropTypes.string,
};

export default NavLink;

我应该如何测试它?我唯一的尝试是:

import NavLink from '../index';

import expect from 'expect';
import { mount } from 'enzyme';
import React from 'react';

describe('<NavLink />', () => {
it('should add active class', () => {
const renderedComponent = mount(<NavLink to="/home" />, { router: { pathname: '/home' } });
expect(renderedComponent.hasClass('active')).toEqual(true);
});
});

它不起作用并返回TypeError:无法读取未定义的属性“isActive”。它肯定需要一些路由器模拟,但我不知道如何编写它。

最佳答案

感谢 @Elon Szopos 的回答,但我设法写了一些更简单的东西(遵循 https://github.com/airbnb/enzyme/pull/62 ):

import NavLink from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';

describe('<NavLink />', () => {
it('should add active class', () => {
const context = { router: { isActive: (a, b) => true } };
const renderedComponent = shallow(<NavLink to="/home" />, { context });
expect(renderedComponent.hasClass('active')).toEqual(true);
});
});

我必须将mount更改为shallow,以便不评估Link,这会给我一个与react-router连接的错误类型错误:router.createHref 不是函数

我宁愿拥有“真正的”react-router 而不仅仅是一个对象,但我不知道如何创建它。

关于reactjs - 如何模拟 react 路由器上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121454/

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