小编典典

如何模拟React-Router上下文

reactjs

我有一个相当简单的react组件(如果路由处于活动状态,链接包装器会添加“ 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;

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

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。它肯定需要一些路由器模拟,但是我不知道如何编写。


阅读 264

收藏
2020-07-22

共1个答案

小编典典

感谢@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);
  });
});

为了不进行评估,我必须更改mountshallowLink这给了我与react-router相关的错误TypeError: router.createHref is not a function

我宁愿拥有一个“真正的”反应路由器,而不仅仅是一个对象,但我不知道如何创建它。

2020-07-22