I'm having an issue testing react-router
starting with an initialEntries
value - the following test fails, and I'm not sure why or what I'm doing wrong.
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());
});
});
The test fails with the following:
● react-router works with enzyme › works with enzyme with starting location
AssertionError: <div>HOME</div>: expected false to be true
I think I understand now... wrapping the component in <MemoryRouter>
doesn't override the existing <Router>
component. The following test passes:
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());
});
});