23
Creating a React component with TDD
Join me in this post as I create a React component using Test Driven Development (TDD) approach.
I am going to create a confirmation component, which has the following features:
- A static title
- A confirmation question - and this can be any question the app would like to confirm
- A button for confirming, supporting an external handler
- A button for canceling, supporting an external handler
Both buttons are not aware of what happens when they are clicked, since it is out of the component’s responsibilities, but the component should enable other components/containers which use it to give it a callback for these buttons.
Here how it should look:
So with that let’s get started.
The process of TDD is a cycle of writing a test => watch it fail => write the minimum code for it to pass => watch it succeed => refactor (if needed) => repeat, and this is what I’m going to practice here. It may, at some point, appear to you as tedious or perhaps impractical, but I insist on doing this by-the-book and leave it to you to decide whether it serves your purposes well, or you’d like to cut some corners on the way.
Off we go with the test file first. I got my Jest testing env running on watch mode and created the component’s directory named “Confirmation” and an “index.test.js” file residing in it.
The first test is pretty abstract. I want to check that rendering the component renders something (anything) to make sure my component exists. In practice I will render my (still not existing) component to see if I can find it on the document by its “dialog” role:
import React from 'react';
import {render} from '@testing-library/react';
describe('Confirmation component', () => {
it('should render', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('dialog')).toBeInTheDocument();
});
});
Well, you guessed it - Jest does not know what “Confirmation” is, and it is right. Let’s create that component just enough to satisfy this test:
import React from 'react';
const Confirmation = () => {
return <div role="dialog"></div>;
};
export default Confirmation;
I imported this Component to my test and it passed now. Great.
Next we would like to have a title for this component. For the purpose of this walkthrough the title is static and should say “Confirmation”. Let’s create a test for it:
it('should have a title saying "Confirmation"', () => {
const {getByText} = render(<Confirmation />);
expect(getByText('Confirmation')).toBeInTheDocument();
});
The test fails, now we write the code to make it pass:
import React from 'react';
const Confirmation = () => {
return (
<div role="dialog">
<h1>Confirmation</h1>
</div>
);
};
export default Confirmation;
Moving to the next feature we want to make sure that there is a confirmation question in this component. I want this question to be dynamic so it can be given from outside the component and I think that having the question as the “children” of the Confirmation component is the right way to go about it, so here’s how the test for that looks like:
it('should have a dynamic confirmation question', () => {
const question = 'Do you confirm?';
const {getByText} = render(<Confirmation>{question}</Confirmation>);
expect(getByText(question)).toBeInTheDocument();
});
Again the test fails so I write the code to make it pass:
import React from 'react';
const Confirmation = ({children}) => {
return (
<div role="dialog">
<h1>Confirmation</h1>
<div>{children}</div>
</div>
);
};
export default Confirmation;
On for the buttons. I will start with the confirm button. We first want to check that there is a button on the component which says “OK”. From now on I will write the test first and the code which satisfy it after:
Test:
it('should have an "OK" button', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('button', {name: 'OK'})).toBeInTheDocument();
});
I’m using the “name” option here since I know there will be at least one more button in this component and I need to be more specific about which I’d like to assert
Component:
import React from 'react';
const Confirmation = ({children}) => {
return (
<div role="dialog">
<h1>Confirmation</h1>
<div>{children}</div>
<button>OK</button>
</div>
);
};
export default Confirmation;
Let’s do the same thing for the “Cancel” button:
Test:
it('should have an "Cancel" button', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('button', {name: 'Cancel'})).toBeInTheDocument();
});
Component:
import React from 'react';
const Confirmation = ({children}) => {
return (
<div role="dialog">
<h1>Confirmation</h1>
<div>{children}</div>
<button>OK</button>
<button>Cancel</button>
</div>
);
};
export default Confirmation;
Ok, nice.
So we got the component rendering what we want (not styled, but that’s another story) and now I would like to make sure I can pass handlers for the buttons of this component from outside, and make sure that they are being called when the buttons are clicked.
I will start from the test for the “OK” button:
it('should be able to receive a handler for the "OK" button and execute it upon click', () => {
const onConfirmationHandler = jest.fn();
const {getByRole} = render(<Confirmation onConfirmation={onConfirmationHandler} />);
const okButton = getByRole('button', {name: 'OK'});
fireEvent.click(okButton);
expect(onConfirmationHandler).toHaveBeenCalled();
});
What I did was to create a spy function, give it to the component as the “onConfirmation” handler, simulate a click on the “OK” button, and assert that the spy has been called.
The test obviously fails, and here is the code to make it happy:
import React from 'react';
const Confirmation = ({children, onConfirmation}) => {
return (
<div role="dialog">
<h1>Confirmation</h1>
<div>{children}</div>
<button onClick={onConfirmation}>
OK
</button>
<button>Cancel</button>
</div>
);
};
export default Confirmation;
Sweet, let’s do the same for the “Cancel” button:
Test:
it('should be able to receive a handler for the "Cancel" button and execute it upon click', () => {
const onCancellationHandler = jest.fn();
const {getByRole} = render(<Confirmation onCancellation={onCancellationHandler} />);
const cancelButton = getByRole('button', {name: 'Cancel'});
fireEvent.click(cancelButton);
expect(onCancellationHandler).toHaveBeenCalled();
});
Component:
import React from 'react';
const Confirmation = ({children, onConfirmation, onCancellation}) => {
return (
<div role="dialog">
<h1>Confirmation</h1>
<div>{children}</div>
<button onClick={onConfirmation}>
OK
</button>
<button onClick={onCancellation}>
Cancel
</button>
</div>
);
};
export default Confirmation;
And here is the full tests file:
import React from 'react';
import {render, fireEvent} from '@testing-library/react';
import Confirmation from '.';
describe('Confirmation component', () => {
it('should render', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('dialog')).toBeInTheDocument();
});
it('should have a title saying "Confirmation"', () => {
const {getByText} = render(<Confirmation />);
expect(getByText('Confirmation')).toBeInTheDocument();
});
it('should have a dynamic confirmation question', () => {
const question = 'Do you confirm?';
const {getByText} = render(<Confirmation>{question}</Confirmation>);
expect(getByText(question)).toBeInTheDocument();
});
it('should have an "OK" button', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('button', {name: 'OK'})).toBeInTheDocument();
});
it('should have an "Cancel" button', () => {
const {getByRole} = render(<Confirmation />);
expect(getByRole('button', {name: 'Cancel'})).toBeInTheDocument();
});
it('should be able to receive a handler for the "OK" button and execute it upon click', () => {
const onConfirmationHandler = jest.fn();
const {getByRole} = render(<Confirmation onConfirmation={onConfirmationHandler} />);
const okButton = getByRole('button', {name: 'OK'});
fireEvent.click(okButton);
expect(onConfirmationHandler).toHaveBeenCalled();
});
it('should be able to receive a handler for the "Cancel" button and execute it upon click', () => {
const onCancellationHandler = jest.fn();
const {getByRole} = render(<Confirmation onCancellation={onCancellationHandler} />);
const cancelButton = getByRole('button', {name: 'Cancel'});
fireEvent.click(cancelButton);
expect(onCancellationHandler).toHaveBeenCalled();
});
});
And I think that that’s it! We have all the building blocks and logic of our component implemented and fully tested:
Yes, I know, the style is off but this is something we can fix after we are certain our building blocks are intact and all works according to spec.
Aside from walking with me in creating this component using TDD, this post is clear evidence TDD can be applied, and rather easily, when developing UI components. TDD will guide you step by step through your component features spec and help you focus on what matters while supplying a safety net for future refactoring. This is really awesome!
As always, if you have any ideas on how to make this better or any other technique, be sure to share with the rest of us!
Cheers
Hey! If you liked what you've just read check out @mattibarzeev on Twitter 🍻
Photo by Jo Szczepanska on Unsplash
23