如何模拟反应路由器上下文 [英] How to mock react-router context

查看:32
本文介绍了如何模拟反应路由器上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有相当简单的反应组件(链接包装器,如果路由处于活动状态,它会添加活动"类):

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.

这篇关于如何模拟反应路由器上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆