我有相当简单的反应组件(链接包装器,如果路由处于活动状态,则会添加“活动”类):
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: Cannot read property 'isActive' of undefined
。它肯定需要一些路由器模拟,但我不知道如何编写它。
感谢@Elon Szopos 的回答,但我设法写了一些更简单的东西(如下https://github.com/airbnb/enzyme/pull/62 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
to shallow
为了不评价Link
这给了我一个与反应路由器连接的错误TypeError: router.createHref is not a function
.
我宁愿拥有“真正的”反应路由器而不仅仅是一个对象,但我不知道如何创建它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)