使用initialEntries测试react-router(带有Enzyme)

时间:2018-02-01 04:22:55

标签: react-router enzyme

我遇到一个以react-router值开头测试initialEntries的问题 - 以下测试失败,我不确定为什么或我做错了什么。

import React, { Component } from 'react';
import { assert } from 'chai';
import { MemoryRouter, BrowserRouter as Router, Route } from 'react-router-dom';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

/* eslint react/prefer-stateless-function: "off" */
class TestApp extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path="/nothome" render={() => 'AWAY'} />
          <Route path="/" exact render={() => 'HOME'} />
        </div>
      </Router>
    );
  }
}

describe('react-router works with enzyme', () => {
  it('works with enzyme with starting location', () => {
    const wrapper = mount(<MemoryRouter initialEntries={['/nothome']} initialIndex={0}><TestApp /></MemoryRouter>);
    assert.isTrue(wrapper.html().includes('AWAY'), wrapper.html());
  });
});

测试失败并带有以下内容:

● react-router works with enzyme › works with enzyme with starting location

    AssertionError: <div>HOME</div>: expected false to be true

1 个答案:

答案 0 :(得分:0)

我想我现在明白了......在<MemoryRouter>中包装组件并不会覆盖现有的<Router>组件。以下测试通过:

import React, { Component } from 'react';
import { assert } from 'chai';
import { MemoryRouter, Route } from 'react-router-dom';
import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

/* eslint react/prefer-stateless-function: "off" */
class TestApp extends Component {
  render() {
    return (
      <div>
        <Route path="/nothome" render={() => 'AWAY'} />
        <Route path="/" exact render={() => 'HOME'} />
      </div>
    );
  }
}

describe('react-router works with enzyme', () => {
  it('works with enzyme with starting location', () => {
    const wrapper = mount(<MemoryRouter initialEntries={['/nothome']} initialIndex={0}><TestApp /></MemoryRouter>);
    assert.isTrue(wrapper.html().includes('AWAY'), wrapper.html());
  });
});