Unit testing 单元测试路由器ONNER/onLeave

Unit testing 单元测试路由器ONNER/onLeave,unit-testing,reactjs,react-router,jestjs,Unit Testing,Reactjs,React Router,Jestjs,我在OneNet/onLeave上运行了一些逻辑。我在OnNet上使用了一些setInterval,并在onLeave上使用clearInterval清除它们 如何对上述情况进行单元测试 <Route component={App} onEnter={onEnterApp} onLeave={onLeaveApp} path="/app"> 下面是我的测试用例,但它失败了 import React from 're

我在OneNet/onLeave上运行了一些逻辑。我在OnNet上使用了一些
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;
    });

});
从“React”导入React;
从“../components/views/App.jsx”导入应用程序;
从“酶”导入{shall,mount,render};
从'chai'导入{expect,assert};
从“sinon”进口sinon;
从“../test_utils/intl enzyme test helper.js”导入{mountWithIntl};
描述('应用程序正确呈现',()=>{
它('安装设置间隔时',()=>{
const wrapper=mountWithIntl();
期望(window.x).存在;
期望(window.y.)存在;
});
它('卸载清除间隔时',()=>{
const wrapper=mountWithIntl();
wrapper.unmount();
expect(window.x).to.not.exist;
expect(window.y).to.not.exist;
});
});

您的
组件的
oneter
onLeave
道具没有绑定到
组件将挂载
组件将卸载
方法,因此仅挂载和卸载
不会调用这些函数

假设您相信React路由器工作正常,您可以测试您的
OneNetApp
onLeaveApp
功能是否正常工作

describe('onEnterApp', () => {
  it('sets x and y', () => {
    onEnterApp();
    expect(global.x).to.exist;
    expect(globa.y).to.exist;
  });
});
如果要验证它们是否在URL与
/app
路径匹配时运行,则需要涉及


您是否尝试过使用
global
而不是
windows
谢谢。这是一个改进,但没有解决问题。render,这是来自Ezyme吗?不,只是
react dom
render。我对酶不太熟悉,不能用它来写答案,但原理应该是一样的。
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();
    });
  });
});
history.push({ pathname: '/foo' })