问题描述
我有一个相当简单的react组件(链接包装器,如果路由处于活动状态,则会添加 active类):
I've got fairly simple react component (Link wrapper which adds 'active' class if route is active):
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;
我应该如何测试?我唯一的尝试是:
How am I supposed to test it? My only attempt was:
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'未定义的
。它肯定需要一些路由器模拟,但是我不知道如何编写它。
It doesn't work and returns TypeError: Cannot read property 'isActive' of undefined
. It definitely needs some router mocking, but I have no idea how to write it.
推荐答案
感谢@Elon Szopos的回答,但我设法写了更简单的内容(遵循 https://github.com/airbnb/enzyme/pull/62):
Thanks @Elon Szopos for your answer but I manage to write something much more simple (following 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 TypeError相关的错误: router.createHref不是一个函数
。
I have to change mount
to shallow
in order not to evaluate Link
which gives me an error connected with the react-router TypeError: router.createHref is not a function
.
我宁愿拥有真正的反应路由器,而不仅仅是一个对象,但我不知道如何创建它。
I would rather have "real" react-router than just an object but I have no idea how to create it.
这篇关于如何模拟React-Router上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!