使用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)的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 MemoryRouter 和 Jest 设置匹配路径? (不是位置或历史)
如何在 mapStateToProps 中使用 useParams?