单元测试 react-router onEnter/onLeave.



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

如何对上述情况进行单元测试?

<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;
    });
});

onEnteronLeave props 与 <App> 组件的componentWillMountcomponentWillUnmount方法无关,因此仅安装和卸载<App>不会调用这些函数。

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

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

如果要验证它们是否在 URL 与/app路径匹配时运行,则需要涉及 <Router>

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' })

最新更新