我正在使用导航,其中使用history.push
复选框的选中或取消选中会导致重定向。我试图编写一个测试来确保这种情况发生,但是在互联网上搜寻类似的东西之后,我终生无法解决。这是我的代码:
App.js
import React, { Component } from 'react';
import { BrowserRouter, Switch, Route, Redirect, withRouter } from 'react-router-dom';
class App extends Component {
render() {
let checkboxChecked = true;
if (this.props.location.pathname === '/path2') {
checkboxChecked = false;
}
return (
<div>
<Switch>
<Route exact path="/path1" render={ () => { return (<h1>Test 1</h1>); }} />
<Route exact path="/path2" render={ () => { return (<h1>Test 2</h1>); }} />
<Redirect from="" to="/path1" />
</Switch>
<input
type="checkbox"
id='theCheckBox'
checked = {checkboxChecked}
onChange={(e) => {
if (e.target.checked === true) {
this.props.history.push("/path1");
} else {
this.props.history.push("/path2");
}
}}
/>
</div>
);
}
}
export default withRouter(App);
App.test.js
import React, { Component } from 'react';
import { createMemoryHistory } from "history";
import { Router, Route } from 'react-router-dom';
import { mount } from "enzyme";
import App from './App';
test('User clicks on checkbox', () => {
const historyObj = createMemoryHistory();
historyObj.location.pathname = '/path1';
const pushSpy = jest.spyOn(historyObj, 'push');
const wrapper = mount(
<Router history={historyObj}>
<App />
</Router>
);
const theCheckBox = wrapper.find('#theCheckBox');
theCheckBox.simulate('change');
expect(pushSpy).toHaveBeenCalledWith('/path2');
});
npm start
的输出
FAIL src/App.test.js
× User clicks on checkbox (33ms)
● User clicks on checkbox
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "/path2"
Received: "/path1"
Number of calls: 1
20 | theCheckBox.simulate('change');
21 |
> 22 | expect(pushSpy).toHaveBeenCalledWith('/path2');
| ^
23 | });
at Object.<anonymous> (src/App.test.js:22:19)
啊,我想通了,这要感谢Github上的以下线程:https://github.com/enzymejs/enzyme/issues/216
仅调用theCheckBox.simulate('change');
来切换复选框是不够的。您还必须将新值传递给它。正确的电话是:
theCheckBox.at(0).simulate('change', { target: { checked: false } });
有了这个更改,我上面的代码按预期工作。