- Prerequisite
- Started with create-react-app
- Write the first test case for the project
- Test Case: User Sign up page
- Add UserSignUpPage.js and UserSignUpPage.spec.js
- Add UserSignUpPage Component in index.js
- Execute Test Case
- Execute Application
Prerequisite
- Install Node.js & npm
Started with create-react-app
npx create-react-app frontend
Write first test case for the project
Add UserSignUpPage.js and UserSignUpPage.spec.js
In src/pages add UserSignUpPage.spec.js
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import { UserSignupPage } from './UserSignUpPage';
// After React-Testing-Library Version 9, clean up part is not needed anymore
describe('userSignupPage', () => {
describe('Layout', () => {
it('has header of Sign Up', () => {
const { container } = render(<UserSignupPage />)
const header = container.querySelector('h1');
expect(header).toHaveTextContent('Sign Up');
})
it('has input for display name', () => {
const {queryByPlaceholderText } = render(<UserSignupPage/>)
const displayNameInput = queryByPlaceholderText('Your display name');
expect(displayNameInput).toBeInTheDocument();
})
})
})
- Test h1 and Input Field
- By Default React Testing Library, execute Test.
UserSignUpPage.js
import React, { Component } from 'react';
export class UserSignupPage extends Component {
render() {
return (
<div><h1>Sign Up</h1>
<div><input placeholder="Your display name" /></div>
</div>
)
}
}
export default UserSignupPage
Add UserSignUpPage Component in index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import { UserSignupPage } from './pages/UserSignUpPage';
ReactDOM.render(
<React.StrictMode>
<UserSignupPage />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
- Add UserSignupPage
Execute Test Case & Execute Application
$ npm test
PASS src/pages/UserSignUpPage.spec.js
userSignupPage
Layout
✓ has header of Sign Up (22ms)
✓ has input for display name (5ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.518s
Ran all test suites related to changed files.
$ npm start