我有一个创建配置文件页面和一个身份验证页面(其中输入通过文本发送的代码(。我想在创建配置文件时导航到身份验证页面。
我有一个用于创建配置文件页面的组件和一个用于身份验证页面的组件。
基于此处的示例。
相关代码:
// CreateProfileComponent.js
import React from 'react';
..
import { withRouter } from "react-router";
class CreateProfile extends React.Component {
constructor(props) {
super(props);
}
handleCreateProfile(e) {
e.preventDefault();
if (condition) {
createProfile(...);
this.props.history.push('/auth');
} else {
// re-render
}
}
render() {
return (
// data-testid="create-profile" - workaround (https://kula.blog/posts/test_on_submit_in_react_testing_library/) for
// https://github.com/jsdom/jsdom/issues/1937
<form onSubmit={this.handleCreateProfile.bind(this)} data-testid="create-profile">
...
</form>
);
}
}
export default withRouter(CreateProfile);
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import CreateProfile from './CreateProfileComponent';
import { TokenEntry } from './TokenEntryComponent';
ReactDOM.render(
<Router>
<ProtectedRoute exact path="/" component={ActivityList} />
<Route path="/login" component={CreateProfile.WrappedComponent} />
<Route path="/auth" component={TokenEntry} />
</Router>,
document.getElementById('root')
);
//createprofilecomponent.test.js
import React from 'react';
import {
LocationProvider,
createMemorySource,
createHistory
} from '@reach/router';
import { render, screen, fireEvent } from '@testing-library/react';
import CreateProfile from '../CreateProfileComponent';
const source = createMemorySource('/login');
const history = createHistory(source);
let displayName = null;
let phoneNumber = null;
let legalAgreement = null;
global.window = { location: { pathname: null } };
function Wrapper({children}) {
return <LocationProvider history={history}>{children}</LocationProvider>;
}
beforeEach(() => {
render(
<CreateProfile.WrappedComponent location={'/'} />,
{ wrapper: Wrapper }
);
});
it("navigates to /auth when good data entered", () => {
// setup
fireEvent.submit(screen.getByTestId('create-profile'));
expect(global.window.location.pathname).toEqual('/auth');
});
我得到了
TypeError: Cannot read property 'push' of undefined
在测试期间和在 Chrome 中。
我错过了什么?
使用 react-router-dom
import { withRouter } from "react-router-dom";
已更改
export default withRouter(CreateProfile);
自
export const CreateProfileWithRouter = withRouter(CreateProfile);
改变
<Route path="/login" component={CreateProfileWithRouter.WrappedComponent} />
自
<Route path="/login" component={CreateProfileWithRouter} />
创建拉取请求以在 withRouter 的文档中包含一个示例。
示例要点