Skip to content

Instantly share code, notes, and snippets.

@joelgriffith
Created July 11, 2017 16:48
Show Gist options
  • Select an option

  • Save joelgriffith/43a4a8195c9fd237a222fe84c2b2e2b4 to your computer and use it in GitHub Desktop.

Select an option

Save joelgriffith/43a4a8195c9fd237a222fe84c2b2e2b4 to your computer and use it in GitHub Desktop.
Simple React login-page for testing
import React, { Component } from 'react';
import './App.css';
class LoginPage extends Component {
constructor() {
super();
this.state = {
username: '',
password: '',
error: '',
};
this.handlePassChange = this.handlePassChange.bind(this);
this.handleUserChange = this.handleUserChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.dismissError = this.dismissError.bind(this);
}
dismissError() {
this.setState({ error: '' });
}
handleSubmit(evt) {
evt.preventDefault();
if (!this.state.username) {
return this.setState({ error: 'Username is required' });
}
if (!this.state.password) {
return this.setState({ error: 'Password is required' });
}
return this.setState({ error: '' });
}
handleUserChange(evt) {
this.setState({
username: evt.target.value,
});
};
handlePassChange(evt) {
this.setState({
password: evt.target.value,
});
}
render() {
// NOTE: I use data-attributes for easier E2E testing
// but you don't need to target those (any css-selector will work)
return (
<div className="Login">
<form onSubmit={this.handleSubmit}>
{
this.state.error &&
<h3 data-test="error" onClick={this.dismissError}>
<button onClick={this.dismissError}>✖</button>
{this.state.error}
</h3>
}
<label>User Name</label>
<input type="text" data-test="username" value={this.state.username} onChange={this.handleUserChange} />
<label>Password</label>
<input type="password" data-test="password" value={this.state.password} onChange={this.handlePassChange} />
<input type="submit" value="Log In" data-test="submit" />
</form>
</div>
);
}
}
export default LoginPage;
@thoth-ky
Copy link
Copy Markdown

Hey, could you write a similar gist on how you would go about writing unit tests for testing this?

@AaravPan
Copy link
Copy Markdown

Yes, This code is good but u can do it more styles.

@sivasaidharmateja
Copy link
Copy Markdown

how to run this file in vs code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment