【问题标题】:Unit Test react-router onEnter/onLeave单元测试 react-router onEnter/onLeave
【发布时间】:2017-01-03 14:34:23
【问题描述】:

我在 onEnter/onLeave 运行了一些逻辑。我在 onEnter 使用了一些 setInterval 并在 onLeave 使用 clearInterval 清除它们。

如何对上述案例进行单元测试?

<Route
        component={App}
        onEnter={onEnterApp}
        onLeave={onLeaveApp}
        path="/app">

下面是我的测试用例,但它失败了,

import React from 'react';
import App from '../components/views/app.jsx';
import {shallow, mount, render} from 'enzyme';
import {expect, assert} from 'chai';
import sinon from 'sinon';
import {mountWithIntl} from '../test_utils/intl-enzyme-test-helper.js';





describe(‘App renders correctly', () => {

    it('When mounting set intervals', () => {
        const wrapper = mountWithIntl(<App/>);
        expect(window.x).to.exist;
        expect(window.y).to.exist;
    });

    it('When unmounting clear intervals', () => {

        const wrapper = mountWithIntl(<App/>);
        wrapper.unmount();
        expect(window.x).to.not.exist;
        expect(window.y).to.not.exist;
    });

});

【问题讨论】:

  • 你试过global而不是windows
  • 谢谢。这是一个改进,但没有解决问题。

标签: unit-testing reactjs react-router jestjs


【解决方案1】:

onEnteronLeave 属性与 &lt;App&gt; 组件的 componentWillMountcomponentWillUnmount 方法无关,因此仅安装和卸载 &lt;App&gt; 不会调用这些函数。

假设您相信 React Router 可以正常工作,您只需测试您的 onEnterApponLeaveApp 函数是否正常工作

describe('onEnterApp', () => {
  it('sets x and y', () => {
    onEnterApp();
    expect(global.x).to.exist;
    expect(globa.y).to.exist;
  });
});

如果您想验证它们是否在 URL 与 /app 路径匹配时运行,那么您需要涉及 &lt;Router&gt;

import createMemoryHistory from 'react-router';

describe('App', () => {
  it('runs onEnterApp when navigating to /app', (done) => {
    const history = createMemoryHistory(['/app']);
    const holder = document.createElement('div');
    render((
      <Router history={history}>
        <Route
          component={App}
          onEnter={onEnterApp}
          onLeave={onLeaveApp}
          path="/app">
      </Router>
    ), holder, () => {
      expect(global.x).to.exist;
      expect(globa.y).to.exist;
      done();
    });
  });
});

测试onLeaveApp 需要您使用history 实例导航到新位置,然后测试所需的全局状态是否存在。

history.push({ pathname: '/foo' })

【讨论】:

  • render ,这是来自酶吗?
  • 不,只是 react-dom 渲染。我对酶不够熟悉,无法用它来写答案,但原理应该是一样的。
猜你喜欢
  • 2017-09-04
  • 1970-01-01
  • 2017-11-02
  • 2018-01-07
  • 2017-08-03
  • 2021-08-11
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多