Skip to content

Instantly share code, notes, and snippets.

@marko-galesic
Created June 26, 2020 21:59
Show Gist options
  • Save marko-galesic/dbecb0f8303b16b129dbd7fcc6004300 to your computer and use it in GitHub Desktop.
Save marko-galesic/dbecb0f8303b16b129dbd7fcc6004300 to your computer and use it in GitHub Desktop.
Testable React form that navigates to another url on submission
import React from 'react';
import { withRouter } from "react-router";
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
phonenumber: '', // avoiding warning for uncontrolled input
displayname: '', // avoiding warning for uncontrolled input
legalAgreement: false,
profileCreated: false,
validPhoneNumber: true,
validDisplayname: true,
validLegalAgreement: true
};
}
handleCreateProfile(e) {
e.preventDefault();
// validation code here
this.props.history.push('/another-url');
}
render() {
return (
// data-testid="create-profile" - workaround (https://tinyurl.com/yb3kjgp2) for
// https://github.com/jsdom/jsdom/issues/1937
<form onSubmit={this.handleCreateProfile.bind(this)} data-testid="login">
<label htmlFor="displayname">Display Name:</label>
<input id="displayname"
name="displayname"
placeholder="John Smith" />
<label htmlFor="password">Password:</label>
<input id="password"
name="password"
placeholder="123456" />
<input type="submit" value="Login" />
</form>
);
}
}
export const FormWithRouter = withRouter(Form);
import React from 'react';
import {
LocationProvider,
createMemorySource,
createHistory
} from '@reach/router';
import { render, screen, fireEvent } from '@testing-library/react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { FormWithRouter } from '../Form';
const source = createMemorySource('/login');
const history = createHistory(source);
let displayName = null;
let password = null;
global.window = { location: { pathname: null } };
function Wrapper({children}) {
return <LocationProvider history={history}>{children}</LocationProvider>;
}
beforeEach(() => {
render(
<Router>
<Route path="/" component={FormWithRouter} />
</Router>,
{ wrapper: Wrapper }
);
displayName = screen.getByLabelText('Display Name:');
password = screen.getByLabelText('Password:');
});
it("navigates to /auth when good data entered", () => {
fireEvent.change(displayName, { target: { value: 'John Smith' } });
fireEvent.change(password, { target: { value: '12345'} });
fireEvent.submit(screen.getByTestId('login'));
expect(global.window.location.pathname).toEqual('/another-url');
});
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { Form } from './Form';
ReactDOM.render(
<Router>
<Route path="/login" component={Form} />
</Router>,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment