React – TDD example

  1. Prerequisite
  2. Started with create-react-app
  3. Write the first test case for the project
    1. Test Case: User Sign up page
    2. Add UserSignUpPage.js and UserSignUpPage.spec.js
    3. Add UserSignUpPage Component in index.js
    4. Execute Test Case
    5. 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

Leave a Reply

Your email address will not be published.

ANOTE.DEV