SlideShare a Scribd company logo
Test Driven Development
with React
Leon Bezuidenhout
🦁🐝
hello@lionbee.net
@lionbeesays
medium.com/@lionbee
Quick survey
✋ Raise your hand if you wrote code today
✋ Keep your hand raised if you wrote unit tests
✋ Keep your hand raised if you did TDD
Overview
● What is software testing
● The tools I use
● What is TDD (Test Driven Development)
● Example of TDD
● Take away
What is software testing?
Software testing is an empirical technical investigation
conducted to provide stakeholders with information about the
quality of the product or service under test
Kaner, Cem (November 17, 2006). Exploratory Testing (PDF). Retrieved from
http://www.kaner.com/pdfs/ETatQAI.pdf
Testing levels
Ham Vocke (26 February 2018). The Practical Test Pyramid. Retrieved from https://martinfowler.com/articles/practical-test-
pyramid.html
Reasons for writing unit tests
● Ensure expected behavior
● Serves as documentation
● Automated regression
Tools for testing
Jest + Enzyme
it("Caption is set", () => {
const caption = 'test';
const wrapper = shallow(
<AwesomeButton caption={caption} />
);
expect(wrapper.text()).toEqual(caption);
});
Example unit test
What is Test Driven Development?
It is an iterative programming workflow whereby you write a
single unit test and then write the code, if required, to make
the test pass. When the test passes you refactor your code,
including the tests, before writing the next test.
TDD workflow
TDD workflow
Test driven development with react
Dan is correct
TDD only works if you have a design
Writing code is a valid way to design
Remember to add tests and refactor
Trivial TDD Example
Build a button component using React that has a configurable caption and on click
event.
Environment
» create-react-app awesome-button --typescript
» cd awesome-button
» npm i -d enzyme enzyme-adapter-react-16 @types/enzyme @types/enzyme-
adapter-react-16
//setupTests.ts
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
configure({ adapter: new Adapter() });
» touch src/AwesomeButton.test.tsx
FAIL src/AwesomeButton.test.tsx
● Test suite failed to run
Your test suite must contain at least one test.
» npm test
// AwesomeButton.test.tsx
describe('AwesomeButton test suite', () => {
it('Environment works', ()=> {})
});
PASS src/awesomebutton.test.tsx
AwesomeButton test suite
✓ Environment works (2ms)
Test Suites: 1 passed, 1 total
import * as React from 'react';
import { shallow } from "enzyme";
import { AwesomeButton } from "./AwesomeButton";
describe("AwesomeButton test suite", () => {
it("Renders", () => {
shallow(<AwesomeButton />);
});
});
FAIL src/AwesomeButton.test.tsx
> 4 | import { AwesomeButton } from "./AwesomeButton";
| ^
// AwesomeButton.tsx
import * as React from 'react';
export function AwesomeButton() {
return <button />;
}
PASS src/awesomebutton.test.ts
AwesomeButton test suite
✓ Renders (5ms)
Test Suites: 1 passed, 1 total
it("Caption is set", () => {
const caption = 'test';
const wrapper = shallow(
<AwesomeButton caption={caption} />
);
expect(wrapper.text()).toEqual(caption);
});
✕ Caption is set (5ms)
● AwesomeButton test suite › Caption is set
expect(received).toEqual(expected) // deep equality
Expected: "test"
Received: ""
interface AwesomeButtonProps {
caption?: string;
}
export function AwesomeButton(props: AwesomeButtonProps) {
return <button>{props.caption}</button>;
}
✓ Caption is set (2ms)
it("onClick handler works", () => {
const mockClick = jest.fn();
const wrapper = shallow(
<AwesomeButton onClick={mockClick} />
);
wrapper.simulate('click');
expect(mockClick).toHaveBeenCalledTimes(1);
});
✕ onClick handler works (47ms)
● AwesomeButton test suite › onClick handler works
expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
interface AwesomeButtonProps {
caption?: string;
onClick?: () => void;
}
export function AwesomeButton(props: AwesomeButtonProps) {
return <button onClick={props.onClick}>
{props.caption}
</button>;
}
✓ onClick handler works (1ms)
it("Clicking with no handler does not raise errors", () => {
const wrapper = shallow(
<AwesomeButton />
);
wrapper.simulate('click');
});
✓ Clicking with no handler does not raise errors
Fixing
it("Caption is set", () => {
const caption = 'test';
const wrapper = shallow(
<AwesomeButton caption={caption} />
);
const captionContainer = wrapper
.find('[data-awesomebutton="caption"]');
expect(captionContainer.text()).toEqual(caption);
});
✕ Caption is set (44ms)
● AwesomeButton test suite › Caption is set
Method “text” is meant to be run on 1 node. 0 found instead.
16 | const captionContainer = wrapper
17 | .find('[data-awesomebutton="caption"]');
> 18 | expect(captionContainer.text()).toEqual(caption);
| ^
export function AwesomeButton(props: AwesomeButtonProps) {
return <button onClick={props.onClick}>
<span data-awesomebutton='caption'>
{props.caption}
</span>
</button>;
}
✓ Caption is set (2ms)
» npm test -- --coverage
PASS src/AwesomeButton.test.tsx
AwesomeButton test suite
✓ Renders (5ms)
✓ Caption is set (5ms)
✓ onClick handler works (2ms)
✓ Clicking with no handler does not raise errors
-------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
AwesomeButton.tsx | 100 | 100 | 100 | 100 | |
-------------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 3.607s
Advantages
● It feels strangely natural
● It can up your engagement
● It’s a good way to pick up an old toolset
● It’s a great way to learn a new language
● It improves design
● It improves estimates
● It’s excellent for pair programming
● When your feature is done, so are your tests
Practice
A code kata is an exercise in programming which helps
programmers hone their skills through practice and repetition.
🔍 TDD code kata javascript
Take this with you
● Testing is as important as the feature
● Test code is as important as feature code
● TDD is about iterative programming
● TDD may make you a better programmer
● Practice
● Be pragmatic
Thank you

More Related Content

What's hot (20)

PDF
An Introduction to Test Driven Development
CodeOps Technologies LLP
 
PPTX
TestNG Framework
Levon Apreyan
 
PPTX
Typescript ppt
akhilsreyas
 
PDF
Introduction to jest
pksjce
 
PDF
Postman
Igor Shubovych
 
PPTX
Javascript
D V BHASKAR REDDY
 
PPTX
Cypress Automation
Susantha Pathirana
 
PDF
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
KEY
Clean code and Code Smells
Mario Sangiorgio
 
PDF
Selenium IDE LOCATORS
Mindfire Solutions
 
PPTX
Agile Testing Strategy
tharindakasun
 
PPTX
Clean code
Duc Nguyen Quang
 
PPTX
Spring boot
sdeeg
 
PDF
e2e testing with cypress
Tomasz Bak
 
PDF
Selenium webdriver interview questions and answers
ITeLearn
 
PPTX
Test your microservices with REST-Assured
Michel Schudel
 
PPTX
Unit Testing in Java
Ahmed M. Gomaa
 
PDF
TypeScript Best Practices
felixbillon
 
An Introduction to Test Driven Development
CodeOps Technologies LLP
 
TestNG Framework
Levon Apreyan
 
Typescript ppt
akhilsreyas
 
Introduction to jest
pksjce
 
Javascript
D V BHASKAR REDDY
 
Cypress Automation
Susantha Pathirana
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Edureka!
 
Clean code and Code Smells
Mario Sangiorgio
 
Selenium IDE LOCATORS
Mindfire Solutions
 
Agile Testing Strategy
tharindakasun
 
Clean code
Duc Nguyen Quang
 
Spring boot
sdeeg
 
e2e testing with cypress
Tomasz Bak
 
Selenium webdriver interview questions and answers
ITeLearn
 
Test your microservices with REST-Assured
Michel Schudel
 
Unit Testing in Java
Ahmed M. Gomaa
 
TypeScript Best Practices
felixbillon
 

Similar to Test driven development with react (20)

PDF
Don't let your tests slow you down
Daniel Irvine
 
PDF
TDD: Develop, Refactor and Release With Confidence
Mehdi Valikhani
 
PDF
Никита Галкин "Testing in Frontend World"
Fwdays
 
PDF
An existential guide to testing React UIs
Emily Bookstein
 
PDF
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
PDF
Test driven development and react js application go hand in hand
Katy Slemon
 
PDF
Testing in FrontEnd World by Nikita Galkin
Sigma Software
 
PDF
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
PDF
Functional Testing for React Native Apps
K. Matthew Dupree
 
PDF
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
PDF
Test-Driven Development in React with Cypress
Josh Justice
 
PDF
The three layers of testing
Bart Waardenburg
 
PDF
Vladyslav Romanchenko "How to keep high code quality without e2e tests"
Dakiry
 
ODP
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
PDF
Developing an Ember Test Strategy - EmberConf 2019
Todd Jordan
 
PDF
TDD step patterns
eduardomg23
 
PPTX
Test Driven Development on Android (Kotlin Kenya)
Danny Preussler
 
PDF
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
PDF
How to push a react js application in production and sleep better
Emanuele Rampichini
 
PDF
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
Don't let your tests slow you down
Daniel Irvine
 
TDD: Develop, Refactor and Release With Confidence
Mehdi Valikhani
 
Никита Галкин "Testing in Frontend World"
Fwdays
 
An existential guide to testing React UIs
Emily Bookstein
 
ES3-2020-06 Test Driven Development (TDD)
David Rodenas
 
Test driven development and react js application go hand in hand
Katy Slemon
 
Testing in FrontEnd World by Nikita Galkin
Sigma Software
 
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Functional Testing for React Native Apps
K. Matthew Dupree
 
TDD CrashCourse Part3: TDD Techniques
David Rodenas
 
Test-Driven Development in React with Cypress
Josh Justice
 
The three layers of testing
Bart Waardenburg
 
Vladyslav Romanchenko "How to keep high code quality without e2e tests"
Dakiry
 
Writing useful automated tests for the single page applications you build
Andrei Sebastian Cîmpean
 
Developing an Ember Test Strategy - EmberConf 2019
Todd Jordan
 
TDD step patterns
eduardomg23
 
Test Driven Development on Android (Kotlin Kenya)
Danny Preussler
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
How to push a react js application in production and sleep better
Emanuele Rampichini
 
Factorio crack FREE Download Latest Version 2025
muhammadwaqaryounus6
 
Ad

Recently uploaded (20)

PPTX
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PDF
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
PPTX
Human Resources Information System (HRIS)
Amity University, Patna
 
PDF
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
PDF
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
PPT
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PPTX
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Java Native Memory Leaks: The Hidden Villain Behind JVM Performance Issues
Tier1 app
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Alarm in Android-Scheduling Timed Tasks Using AlarmManager in Android.pdf
Nabin Dhakal
 
Human Resources Information System (HRIS)
Amity University, Patna
 
Salesforce CRM Services.VALiNTRY360
VALiNTRY360
 
Efficient, Automated Claims Processing Software for Insurers
Insurance Tech Services
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Feb 2021 Cohesity first pitch presentation.pptx
enginsayin1
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
MergeSortfbsjbjsfk sdfik k
RafishaikIT02044
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
MiniTool Power Data Recovery Full Crack Latest 2025
muhammadgurbazkhan
 
Ad

Test driven development with react

  • 1. Test Driven Development with React Leon Bezuidenhout 🦁🐝 [email protected] @lionbeesays medium.com/@lionbee
  • 2. Quick survey ✋ Raise your hand if you wrote code today ✋ Keep your hand raised if you wrote unit tests ✋ Keep your hand raised if you did TDD
  • 3. Overview ● What is software testing ● The tools I use ● What is TDD (Test Driven Development) ● Example of TDD ● Take away
  • 4. What is software testing? Software testing is an empirical technical investigation conducted to provide stakeholders with information about the quality of the product or service under test Kaner, Cem (November 17, 2006). Exploratory Testing (PDF). Retrieved from http://www.kaner.com/pdfs/ETatQAI.pdf
  • 5. Testing levels Ham Vocke (26 February 2018). The Practical Test Pyramid. Retrieved from https://martinfowler.com/articles/practical-test- pyramid.html
  • 6. Reasons for writing unit tests ● Ensure expected behavior ● Serves as documentation ● Automated regression
  • 8. it("Caption is set", () => { const caption = 'test'; const wrapper = shallow( <AwesomeButton caption={caption} /> ); expect(wrapper.text()).toEqual(caption); }); Example unit test
  • 9. What is Test Driven Development? It is an iterative programming workflow whereby you write a single unit test and then write the code, if required, to make the test pass. When the test passes you refactor your code, including the tests, before writing the next test.
  • 14. TDD only works if you have a design
  • 15. Writing code is a valid way to design Remember to add tests and refactor
  • 16. Trivial TDD Example Build a button component using React that has a configurable caption and on click event.
  • 17. Environment » create-react-app awesome-button --typescript » cd awesome-button » npm i -d enzyme enzyme-adapter-react-16 @types/enzyme @types/enzyme- adapter-react-16 //setupTests.ts import { configure } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; configure({ adapter: new Adapter() }); » touch src/AwesomeButton.test.tsx
  • 18. FAIL src/AwesomeButton.test.tsx ● Test suite failed to run Your test suite must contain at least one test. » npm test
  • 19. // AwesomeButton.test.tsx describe('AwesomeButton test suite', () => { it('Environment works', ()=> {}) }); PASS src/awesomebutton.test.tsx AwesomeButton test suite ✓ Environment works (2ms) Test Suites: 1 passed, 1 total
  • 20. import * as React from 'react'; import { shallow } from "enzyme"; import { AwesomeButton } from "./AwesomeButton"; describe("AwesomeButton test suite", () => { it("Renders", () => { shallow(<AwesomeButton />); }); }); FAIL src/AwesomeButton.test.tsx > 4 | import { AwesomeButton } from "./AwesomeButton"; | ^
  • 21. // AwesomeButton.tsx import * as React from 'react'; export function AwesomeButton() { return <button />; } PASS src/awesomebutton.test.ts AwesomeButton test suite ✓ Renders (5ms) Test Suites: 1 passed, 1 total
  • 22. it("Caption is set", () => { const caption = 'test'; const wrapper = shallow( <AwesomeButton caption={caption} /> ); expect(wrapper.text()).toEqual(caption); }); ✕ Caption is set (5ms) ● AwesomeButton test suite › Caption is set expect(received).toEqual(expected) // deep equality Expected: "test" Received: ""
  • 23. interface AwesomeButtonProps { caption?: string; } export function AwesomeButton(props: AwesomeButtonProps) { return <button>{props.caption}</button>; } ✓ Caption is set (2ms)
  • 24. it("onClick handler works", () => { const mockClick = jest.fn(); const wrapper = shallow( <AwesomeButton onClick={mockClick} /> ); wrapper.simulate('click'); expect(mockClick).toHaveBeenCalledTimes(1); }); ✕ onClick handler works (47ms) ● AwesomeButton test suite › onClick handler works expect(jest.fn()).toHaveBeenCalledTimes(expected) Expected number of calls: 1 Received number of calls: 0
  • 25. interface AwesomeButtonProps { caption?: string; onClick?: () => void; } export function AwesomeButton(props: AwesomeButtonProps) { return <button onClick={props.onClick}> {props.caption} </button>; } ✓ onClick handler works (1ms)
  • 26. it("Clicking with no handler does not raise errors", () => { const wrapper = shallow( <AwesomeButton /> ); wrapper.simulate('click'); }); ✓ Clicking with no handler does not raise errors
  • 28. it("Caption is set", () => { const caption = 'test'; const wrapper = shallow( <AwesomeButton caption={caption} /> ); const captionContainer = wrapper .find('[data-awesomebutton="caption"]'); expect(captionContainer.text()).toEqual(caption); }); ✕ Caption is set (44ms) ● AwesomeButton test suite › Caption is set Method “text” is meant to be run on 1 node. 0 found instead. 16 | const captionContainer = wrapper 17 | .find('[data-awesomebutton="caption"]'); > 18 | expect(captionContainer.text()).toEqual(caption); | ^
  • 29. export function AwesomeButton(props: AwesomeButtonProps) { return <button onClick={props.onClick}> <span data-awesomebutton='caption'> {props.caption} </span> </button>; } ✓ Caption is set (2ms)
  • 30. » npm test -- --coverage PASS src/AwesomeButton.test.tsx AwesomeButton test suite ✓ Renders (5ms) ✓ Caption is set (5ms) ✓ onClick handler works (2ms) ✓ Clicking with no handler does not raise errors -------------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | -------------------|----------|----------|----------|----------|-------------------| All files | 100 | 100 | 100 | 100 | | AwesomeButton.tsx | 100 | 100 | 100 | 100 | | -------------------|----------|----------|----------|----------|-------------------| Test Suites: 1 passed, 1 total Tests: 4 passed, 4 total Snapshots: 0 total Time: 3.607s
  • 31. Advantages ● It feels strangely natural ● It can up your engagement ● It’s a good way to pick up an old toolset ● It’s a great way to learn a new language ● It improves design ● It improves estimates ● It’s excellent for pair programming ● When your feature is done, so are your tests
  • 32. Practice A code kata is an exercise in programming which helps programmers hone their skills through practice and repetition. 🔍 TDD code kata javascript
  • 33. Take this with you ● Testing is as important as the feature ● Test code is as important as feature code ● TDD is about iterative programming ● TDD may make you a better programmer ● Practice ● Be pragmatic