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
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

Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and CucumberTest Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
Rhoynar Software Consulting
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean Code
Petra Barus
 
Designing Effective Tests with React Testing Library - React Day Berlin 2022
Designing Effective Tests with React Testing Library - React Day Berlin 2022Designing Effective Tests with React Testing Library - React Day Berlin 2022
Designing Effective Tests with React Testing Library - React Day Berlin 2022
Josh Justice
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
Pavan Kumar
 
Full stack web development
Full stack web developmentFull stack web development
Full stack web development
Crampete
 
Mobile UI Testing using Appium and Docker
Mobile UI Testing using Appium and DockerMobile UI Testing using Appium and Docker
Mobile UI Testing using Appium and Docker
Moataz Nabil
 
Selenium
SeleniumSelenium
Cucumber ppt
Cucumber pptCucumber ppt
Cucumber ppt
Qwinix Technologies
 
Selenium Presentation at Engineering Colleges
Selenium Presentation at Engineering CollegesSelenium Presentation at Engineering Colleges
Selenium Presentation at Engineering Colleges
Vijay Rangaiah
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting Started
Tracy Lee
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
Gabriele Lana
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
Pekka Klärck
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
Knoldus Inc.
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
Cuelogic Technologies Pvt. Ltd.
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
🐕 Łukasz Ostrowski
 
Playwright: A New Test Automation Framework for the Modern Web
Playwright: A New Test Automation Framework for the Modern WebPlaywright: A New Test Automation Framework for the Modern Web
Playwright: A New Test Automation Framework for the Modern Web
Applitools
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
Return on Intelligence
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
Vladimir Parfenov
 
Introduction to Automation Testing and Selenium overiew
Introduction to Automation Testing and Selenium overiewIntroduction to Automation Testing and Selenium overiew
Introduction to Automation Testing and Selenium overiew
Disha Srivastava
 
API Test Automation
API Test Automation API Test Automation
API Test Automation
SQALab
 

What's hot (20)

Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and CucumberTest Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
 
Javascript Clean Code
Javascript Clean CodeJavascript Clean Code
Javascript Clean Code
 
Designing Effective Tests with React Testing Library - React Day Berlin 2022
Designing Effective Tests with React Testing Library - React Day Berlin 2022Designing Effective Tests with React Testing Library - React Day Berlin 2022
Designing Effective Tests with React Testing Library - React Day Berlin 2022
 
Selenium ppt
Selenium pptSelenium ppt
Selenium ppt
 
Full stack web development
Full stack web developmentFull stack web development
Full stack web development
 
Mobile UI Testing using Appium and Docker
Mobile UI Testing using Appium and DockerMobile UI Testing using Appium and Docker
Mobile UI Testing using Appium and Docker
 
Selenium
SeleniumSelenium
Selenium
 
Cucumber ppt
Cucumber pptCucumber ppt
Cucumber ppt
 
Selenium Presentation at Engineering Colleges
Selenium Presentation at Engineering CollegesSelenium Presentation at Engineering Colleges
Selenium Presentation at Engineering Colleges
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting Started
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Robot Framework Introduction
Robot Framework IntroductionRobot Framework Introduction
Robot Framework Introduction
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Universal React apps in Next.js
Universal React apps in Next.jsUniversal React apps in Next.js
Universal React apps in Next.js
 
Playwright: A New Test Automation Framework for the Modern Web
Playwright: A New Test Automation Framework for the Modern WebPlaywright: A New Test Automation Framework for the Modern Web
Playwright: A New Test Automation Framework for the Modern Web
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Flutter Intro
Flutter IntroFlutter Intro
Flutter Intro
 
Introduction to Automation Testing and Selenium overiew
Introduction to Automation Testing and Selenium overiewIntroduction to Automation Testing and Selenium overiew
Introduction to Automation Testing and Selenium overiew
 
API Test Automation
API Test Automation API Test Automation
API Test Automation
 

Similar to Test driven development with react

MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
Hans Jones
 
Unit test
Unit testUnit test
Unit test
Tran Duc
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"
Fwdays
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
ericholscher
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
atesgoral
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
Sigma Software
 
Unit testing
Unit testingUnit testing
Unit testing
Pooya Sagharchiha
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
ericholscher
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
Anna Khabibullina
 
Test
TestTest
Test
Eddie Kao
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
All Things Open
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anil
guest3373d3
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
subhasis100
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorial
guest37ae7f
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
subhasis100
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
vinayaka.nadiger
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 features
krishna3032
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorial
sasidhar
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
rosaleenm
 
QA Fest 2019. Антон Молдован. Load testing which you always wanted
QA Fest 2019. Антон Молдован. Load testing which you always wantedQA Fest 2019. Антон Молдован. Load testing which you always wanted
QA Fest 2019. Антон Молдован. Load testing which you always wanted
QAFest
 

Similar to Test driven development with react (20)

MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit test
Unit testUnit test
Unit test
 
Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"Никита Галкин "Testing in Frontend World"
Никита Галкин "Testing in Frontend World"
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
Testing in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita GalkinTesting in FrontEnd World by Nikita Galkin
Testing in FrontEnd World by Nikita Galkin
 
Unit testing
Unit testingUnit testing
Unit testing
 
Making the most of your Test Suite
Making the most of your Test SuiteMaking the most of your Test Suite
Making the most of your Test Suite
 
In search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
 
Test
TestTest
Test
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anil
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorial
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 features
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorial
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
QA Fest 2019. Антон Молдован. Load testing which you always wanted
QA Fest 2019. Антон Молдован. Load testing which you always wantedQA Fest 2019. Антон Молдован. Load testing which you always wanted
QA Fest 2019. Антон Молдован. Load testing which you always wanted
 

Recently uploaded

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
Massimo Artizzu
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
Quickdice ERP
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
NishanthaBulumulla1
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Julian Hyde
 

Recently uploaded (20)

J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Liberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptxLiberarsi dai framework con i Web Component.pptx
Liberarsi dai framework con i Web Component.pptx
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesE-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian Companies
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
YAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring detailsYAML crash COURSE how to write yaml file for adding configuring details
YAML crash COURSE how to write yaml file for adding configuring details
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)Measures in SQL (SIGMOD 2024, Santiago, Chile)
Measures in SQL (SIGMOD 2024, Santiago, Chile)
 

Test driven development with react

  • 1. Test Driven Development with React Leon Bezuidenhout 🦁🐝 hello@lionbee.net @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.
  • 12.
  • 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