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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用initialEntries测试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
答案

我想我现在明白了......在<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());
  });
});

以上是关于使用initialEntries测试react-router(带有Enzyme)的主要内容,如果未能解决你的问题,请参考以下文章

使用`setVariables`后中继生成无效查询-我做错了啥吗?

React 路由基本配置

对某些案例问题做出反应警告计算匹配?

如何在初始渲染后重新渲染自定义钩子

在 Reactjs 的页面中添加会话超时