如何使用Jest和Enzyme测试是否根据URL更改渲染了子React组件

时间:2019-03-21 03:41:55

标签: reactjs react-router jestjs enzyme react-router-v4

我想测试将URL更改为不存在的路径时是否呈现NotFoundScreen组件

这是我的App组件:

import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import './App.css';
import HomeScreen from '../HomeScreen';
import NotFoundScreen from '../NotFoundScreen';

export default class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route path="/" exact component={HomeScreen} />
          <Route component={NotFoundScreen} />
        </Switch>
      </BrowserRouter>
    );
  }
}

这是我无法正常工作的测试:

  it('render NotFoundScreen when goes to a wrong path', async () => {
    const wrapper = mount(<App />);

    window.location.href = 'http://localhost:3000/wrongpath';
    await wrapper.update();

    expect(wrapper.find(NotFoundScreen).length).toEqual(1);
  });

当我更改为检查HomeScreen组件通过时,其wrapper不会根据URL更新

expect(wrapper.find(HomeScreen).length).toEqual(1);

1 个答案:

答案 0 :(得分:0)

看来问题出在jsdom。

这是解决方法:

  it('render NotFoundScreen when goes to a wrong path', async () => {
    history.replaceState({}, 'WrongPath', '/wrongpath');
    const wrapper = mount(<App />);
    expect(wrapper.find(NotFoundScreen).length).toEqual(1);
  });