我想测试将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);
答案 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);
});