Front End Workshops
React Testing
Cristina Hernández García
chernandez@visual-engin.com
Mario García Martín
mgarcia@visual-engin.com
JavaScript Testing
Remember, remember...
Testing basics
Tools we’ll be using
describe("Use describe to group similar tests", function() {
});
Test framework Assertions library Test spies, stubs and mocks
*More info at http://mochajs.org/, http://chaijs.com/, and http://sinonjs.org/
describe
suite hooks
it
expect
beforeEach(function() {});
afterEach(function() {});
it("use it to test an attribute of a target", function() {
});
// use expect to make an assertion about a target
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
Test Driven Development (TDD)
The cycle of TDD
Benefits of TDD
Produces code that works
Honors the Single Responsibility Principle
Forces conscious development
Productivity boost
Run tests
Write a
test
Run tests
Make the
test pass
Refactor
Test Driven Development (TDD)
The cycle of TDD
Benefits of TDD
Produces code that works
Honors the Single Responsibility Principle
Forces conscious development
Productivity boost
Run tests
Write a
test
Run tests
Make the
test pass
Refactor
Testing React applications
What’s different?
React testing - Particularities (1 of 2)
Although not always required, sometimes it’s necessary to have a full DOM
API.
Components are rendered to a VDOM...
No need to fully render our components while testing!
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = {
userAgent: 'node.js'
};
For console-based testing environments you can use the jsdom library to mock
the DOM document.
React testing - Particularities
Events simulation is needed
Components are rendered to a VDOM...
Higher level components can be tested in isolation. Shallow rendering.
View
ViewView
View View View View View
Lets you render a
component “one level
deep”.
You don’t have to worry
about the behavior of
child components.
React test utilities
Makes it easy to test React components in
the testing framework of your choice.
React test utilities (1 of 3) (react-addons-test-utils)
ReactComponent renderIntoDocument(ReactElement instance)
Render a component into a detached DOM node in the document.
Requires a full DOM API available at the global scope.
It does not require a DOM API.
ReactShallowRenderer
createRenderer()
shallowRenderer.render(ReactElement element)
ReactElement shallowRenderer.getRenderOutput()
Rendering components
Shallow rendering
React test utilities (2 of 3) (react-addons-test-utils)
Shallow rendering example
// MyComponent.js
import React, { Component } from
'react';
import Subcomponent from
'./Subcomponent';
class MyComponent extends Component {
render() {
return (
<div>
<span className="heading">
Title
</span>
<Subcomponent foo="bar" />
</div>
);
}
}
export default MyComponent;
// MyComponent.spec.js
import React from 'react';
import TestUtils from
'react-addons-test-utils';
import MyComponent from 'mycomponent';
const renderer =
TestUtils.createRenderer();
renderer.render(<MyComponent />);
const result =
renderer.getRenderOutput();
expect(result.type).to.equal('div');
expect(result.props.children).to.eql([
<span className="heading">Title</span>,
<Subcomponent foo="bar" />
]);
React test utilities (3 of 3) (react-addons-test-utils)
findAllInRenderedTree
scryRenderedDOMComponentsWithClass
findRenderedDOMComponentWithClass
scryRenderedDOMComponentsWithTag
findRenderedDOMComponentWithTag
scryRenderedDOMComponentsWithType
findRenderedDOMComponentWithType
Simulate an event dispatch on a DOM node with optional event data.
Simulate.{eventName}(DOMElement element, [object eventData])
Simulating React synthetic events
The rendered components interface...
Enzyme
JavaScript Testing utility for React.
Enzyme - Introduction
Now, with 150% neater interface!
.find(selector)
.findWhere(predicate)
.state([key])
.setState(nextState)
.prop([key])
.setProps(nextProps)
.parent()
.children()
.simulate(event[,
data])
.update()
.debug()
*The render function may not have all the methods advertised
Mimicks jQuery’s API DOM manipulation and traversal.
rendermountshallow
Enzyme - Shallow rendering
shallow(node[, options]) => ShallowWrapper
*More info at http://airbnb.io/enzyme/docs/api/shallow.html
const row = shallow(<TableRow columns={5} />)
// Using prop to retrieve the columns
property
expect(row.prop('columns')).to.eql(5);
// Using 'at' to retrieve the forth column's
content
expect(row.find(TableColumn).at(3).prop('content')).to.exist;
// Using first and text to retrieve the columns text
content
expect(row.find(TableColumn).first().text()).to.eql('First column');
// Simulating events
const button = shallow(<MyButton
/>);
button.simulate('click');
expect(button.state('myActionWasPerformed')).to.be.true;
Enzyme - Full DOM rendering
mount(node[, options]) => ReactWrapper
*More info at http://airbnb.io/enzyme/docs/api/mount.html
Use it when interacting with DOM or testing full lifecycle (componentDidMount).
it('calls componentDidMount', function() {
spy(Foo.prototype, 'componentDidMount');
const wrapper = mount(<Foo />);
expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true);
});
it('allows us to set props', function() {
const wrapper = mount(<Foo bar='baz' />);
expect(wrapper.prop('bar')).to.equal('baz');
wrapper.setProps({ bar: 'foo' });
expect(wrapper.props('bar')).to.equal('foo');
});
Requires a full DOM API available at the global scope.
Enzyme - Static rendered markup
render(node[, options]) => CheerioWrapper
*More info at http://airbnb.io/enzyme/docs/api/render.html
Use it to render react components into static HTML (Uses Cheerio library).
it('renders three .foo-bar', function() {
const wrapper = render(<Foo />);
expect(wrapper.find('.foo-bar')).to.have.length(3);
});
it('rendered the title', function() {
const wrapper = render(<Foo title="unique" />);
expect(wrapper.text()).to.contain("unique");
});
Hands on code
Simpsons Wheel
Simpsons Wheel - General overview
App
generateRandInfo(<value>)
type: GENERATE_RANDINFO
payload: { value: 1, timestamp: 1234}
Reducers
STATE
randInfo: { value: 1, timestamp: 1234 }
Wheel
Button
Simpsons Wheel - Component details (1 of 2)
App component
Renders Wheel component, passing items prop
Renders Button component, passing max prop
Button component
Receives a max prop
When clicked, computes a random value between 1 and max
Calls action creator with the random number
Simpsons Wheel - Component details (2 of 2)
Wheel component
Renders the images
Stores the carousel
rotation in its state
Listens to Redux state
changes
Updates the rotation when
receives new props
Thanks for your time!
Do you have any questions?
Workshop 23: ReactJS, React & Redux testing

More Related Content

PDF
Workshop 26: React Native - The Native Side
PDF
Workshop 17: EmberJS parte II
PPTX
Workshop 1: Good practices in JavaScript
PDF
Workshop 25: React Native - Components
PDF
Workshop 14: AngularJS Parte III
PDF
Workshop 24: React Native Introduction
PDF
Workshop 13: AngularJS Parte II
PDF
Workshop 19: ReactJS Introduction
Workshop 26: React Native - The Native Side
Workshop 17: EmberJS parte II
Workshop 1: Good practices in JavaScript
Workshop 25: React Native - Components
Workshop 14: AngularJS Parte III
Workshop 24: React Native Introduction
Workshop 13: AngularJS Parte II
Workshop 19: ReactJS Introduction

What's hot (20)

PDF
Workshop 20: ReactJS Part II Flux Pattern & Redux
PDF
Workshop 22: React-Redux Middleware
PDF
Workshop 5: JavaScript testing
PDF
Redux Sagas - React Alicante
PDF
Protocol-Oriented MVVM (extended edition)
PDF
Reactive, component 그리고 angular2
PDF
Swift Delhi: Practical POP
PDF
Practical Protocol-Oriented-Programming
PDF
Workshop 12: AngularJS Parte I
PDF
Protocol-Oriented MVVM
PDF
«От экспериментов с инфраструктурой до внедрения в продакшен»​
PDF
Workshop 8: Templating: Handlebars, DustJS
PDF
Using React, Redux and Saga with Lottoland APIs
PDF
Workshop 3: JavaScript build tools
PDF
How Angular2 Can Improve Your AngularJS Apps Today!
PPTX
Typescript barcelona
PDF
Building scalable applications with angular js
PDF
React Native One Day
PDF
Async JavaScript Unit Testing
PDF
Kotlin Delegates in practice - Kotlin community conf
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 22: React-Redux Middleware
Workshop 5: JavaScript testing
Redux Sagas - React Alicante
Protocol-Oriented MVVM (extended edition)
Reactive, component 그리고 angular2
Swift Delhi: Practical POP
Practical Protocol-Oriented-Programming
Workshop 12: AngularJS Parte I
Protocol-Oriented MVVM
«От экспериментов с инфраструктурой до внедрения в продакшен»​
Workshop 8: Templating: Handlebars, DustJS
Using React, Redux and Saga with Lottoland APIs
Workshop 3: JavaScript build tools
How Angular2 Can Improve Your AngularJS Apps Today!
Typescript barcelona
Building scalable applications with angular js
React Native One Day
Async JavaScript Unit Testing
Kotlin Delegates in practice - Kotlin community conf
Ad

Similar to Workshop 23: ReactJS, React & Redux testing (20)

PDF
Annotation Processing
PPTX
Protractor framework architecture with example
PPTX
In search of JavaScript code quality: unit testing
KEY
Javascript unit testing, yes we can e big
PPTX
Nevermore Unit Testing
PPTX
Junit_.pptx
PDF
Fundamental Concepts of React JS for Beginners.pdf
KEY
JavaScript Growing Up
PPT
JavaScript Basics
PDF
Javascript tdd byandreapaciolla
PDF
Javascript Frameworks for Joomla
PPT
比XML更好用的Java Annotation
ODP
Grails unit testing
PPTX
Adding a modern twist to legacy web applications
PDF
MeetJS Summit 2016: React.js enlightenment
ODP
Bring the fun back to java
PDF
Release with confidence
PDF
Build Web Apps using Node.js
PPTX
react-slides.pptx
ODP
Unit Testing and Coverage for AngularJS
Annotation Processing
Protractor framework architecture with example
In search of JavaScript code quality: unit testing
Javascript unit testing, yes we can e big
Nevermore Unit Testing
Junit_.pptx
Fundamental Concepts of React JS for Beginners.pdf
JavaScript Growing Up
JavaScript Basics
Javascript tdd byandreapaciolla
Javascript Frameworks for Joomla
比XML更好用的Java Annotation
Grails unit testing
Adding a modern twist to legacy web applications
MeetJS Summit 2016: React.js enlightenment
Bring the fun back to java
Release with confidence
Build Web Apps using Node.js
react-slides.pptx
Unit Testing and Coverage for AngularJS
Ad

More from Visual Engineering (17)

PDF
Workshop 27: Isomorphic web apps with ReactJS
PDF
Workshop iOS 4: Closures, generics & operators
PDF
Workshop iOS 3: Testing, protocolos y extensiones
PDF
Workshop iOS 2: Swift - Structures
PDF
Workhop iOS 1: Fundamentos de Swift
PDF
Workshop 22: ReactJS Redux Advanced
PDF
Workshop 21: React Router
PDF
Workshop 18: CSS Animations & cool effects
PDF
Workshop 16: EmberJS Parte I
PDF
Workshop 15: Ionic framework
PDF
Workshop 11: Trendy web designs & prototyping
PDF
Workshop 10: ECMAScript 6
PDF
Workshop 9: BackboneJS y patrones MVC
PDF
Workshop 7: Single Page Applications
PDF
Workshop 6: Designer tools
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
PDF
Workshop 2: JavaScript Design Patterns
Workshop 27: Isomorphic web apps with ReactJS
Workshop iOS 4: Closures, generics & operators
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 2: Swift - Structures
Workhop iOS 1: Fundamentos de Swift
Workshop 22: ReactJS Redux Advanced
Workshop 21: React Router
Workshop 18: CSS Animations & cool effects
Workshop 16: EmberJS Parte I
Workshop 15: Ionic framework
Workshop 11: Trendy web designs & prototyping
Workshop 10: ECMAScript 6
Workshop 9: BackboneJS y patrones MVC
Workshop 7: Single Page Applications
Workshop 6: Designer tools
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 2: JavaScript Design Patterns

Recently uploaded (20)

PPTX
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
PDF
Engineering Document Management System (EDMS)
PDF
WhatsApp Chatbots The Key to Scalable Customer Support.pdf
PPTX
WJQSJXNAZJVCVSAXJHBZKSJXKJKXJSBHJBJEHHJB
PDF
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
PPTX
AI Tools Revolutionizing Software Development Workflows
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PPTX
SAP Business AI_L1 Overview_EXTERNAL.pptx
PPTX
FLIGHT TICKET API | API INTEGRATION PLATFORM
PDF
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
PPTX
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
PPTX
Human-Computer Interaction for Lecture 1
PDF
IT Consulting Services to Secure Future Growth
PDF
Mobile App Backend Development with WordPress REST API: The Complete eBook
PPTX
Chapter_05_System Modeling for software engineering
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PPTX
Why 2025 Is the Best Year to Hire Software Developers in India
PPTX
Comprehensive Guide to Digital Image Processing Concepts and Applications
PDF
infoteam HELLAS company profile 2025 presentation
PDF
What Makes a Great Data Visualization Consulting Service.pdf
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
Engineering Document Management System (EDMS)
WhatsApp Chatbots The Key to Scalable Customer Support.pdf
WJQSJXNAZJVCVSAXJHBZKSJXKJKXJSBHJBJEHHJB
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
AI Tools Revolutionizing Software Development Workflows
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
SAP Business AI_L1 Overview_EXTERNAL.pptx
FLIGHT TICKET API | API INTEGRATION PLATFORM
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
Streamlining Project Management in the AV Industry with D-Tools for Zoho CRM ...
Human-Computer Interaction for Lecture 1
IT Consulting Services to Secure Future Growth
Mobile App Backend Development with WordPress REST API: The Complete eBook
Chapter_05_System Modeling for software engineering
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
Why 2025 Is the Best Year to Hire Software Developers in India
Comprehensive Guide to Digital Image Processing Concepts and Applications
infoteam HELLAS company profile 2025 presentation
What Makes a Great Data Visualization Consulting Service.pdf

Workshop 23: ReactJS, React & Redux testing

  • 1. Front End Workshops React Testing Cristina Hernández García [email protected] Mario García Martín [email protected]
  • 3. Testing basics Tools we’ll be using describe("Use describe to group similar tests", function() { }); Test framework Assertions library Test spies, stubs and mocks *More info at http://mochajs.org/, http://chaijs.com/, and http://sinonjs.org/ describe suite hooks it expect beforeEach(function() {}); afterEach(function() {}); it("use it to test an attribute of a target", function() { }); // use expect to make an assertion about a target expect(foo).to.be.a('string'); expect(foo).to.equal('bar');
  • 4. Test Driven Development (TDD) The cycle of TDD Benefits of TDD Produces code that works Honors the Single Responsibility Principle Forces conscious development Productivity boost Run tests Write a test Run tests Make the test pass Refactor
  • 5. Test Driven Development (TDD) The cycle of TDD Benefits of TDD Produces code that works Honors the Single Responsibility Principle Forces conscious development Productivity boost Run tests Write a test Run tests Make the test pass Refactor
  • 7. React testing - Particularities (1 of 2) Although not always required, sometimes it’s necessary to have a full DOM API. Components are rendered to a VDOM... No need to fully render our components while testing! global.document = jsdom.jsdom('<!doctype html><html><body></body></html>'); global.window = global.document.defaultView; global.navigator = { userAgent: 'node.js' }; For console-based testing environments you can use the jsdom library to mock the DOM document.
  • 8. React testing - Particularities Events simulation is needed Components are rendered to a VDOM... Higher level components can be tested in isolation. Shallow rendering. View ViewView View View View View View Lets you render a component “one level deep”. You don’t have to worry about the behavior of child components.
  • 9. React test utilities Makes it easy to test React components in the testing framework of your choice.
  • 10. React test utilities (1 of 3) (react-addons-test-utils) ReactComponent renderIntoDocument(ReactElement instance) Render a component into a detached DOM node in the document. Requires a full DOM API available at the global scope. It does not require a DOM API. ReactShallowRenderer createRenderer() shallowRenderer.render(ReactElement element) ReactElement shallowRenderer.getRenderOutput() Rendering components Shallow rendering
  • 11. React test utilities (2 of 3) (react-addons-test-utils) Shallow rendering example // MyComponent.js import React, { Component } from 'react'; import Subcomponent from './Subcomponent'; class MyComponent extends Component { render() { return ( <div> <span className="heading"> Title </span> <Subcomponent foo="bar" /> </div> ); } } export default MyComponent; // MyComponent.spec.js import React from 'react'; import TestUtils from 'react-addons-test-utils'; import MyComponent from 'mycomponent'; const renderer = TestUtils.createRenderer(); renderer.render(<MyComponent />); const result = renderer.getRenderOutput(); expect(result.type).to.equal('div'); expect(result.props.children).to.eql([ <span className="heading">Title</span>, <Subcomponent foo="bar" /> ]);
  • 12. React test utilities (3 of 3) (react-addons-test-utils) findAllInRenderedTree scryRenderedDOMComponentsWithClass findRenderedDOMComponentWithClass scryRenderedDOMComponentsWithTag findRenderedDOMComponentWithTag scryRenderedDOMComponentsWithType findRenderedDOMComponentWithType Simulate an event dispatch on a DOM node with optional event data. Simulate.{eventName}(DOMElement element, [object eventData]) Simulating React synthetic events The rendered components interface...
  • 14. Enzyme - Introduction Now, with 150% neater interface! .find(selector) .findWhere(predicate) .state([key]) .setState(nextState) .prop([key]) .setProps(nextProps) .parent() .children() .simulate(event[, data]) .update() .debug() *The render function may not have all the methods advertised Mimicks jQuery’s API DOM manipulation and traversal. rendermountshallow
  • 15. Enzyme - Shallow rendering shallow(node[, options]) => ShallowWrapper *More info at http://airbnb.io/enzyme/docs/api/shallow.html const row = shallow(<TableRow columns={5} />) // Using prop to retrieve the columns property expect(row.prop('columns')).to.eql(5); // Using 'at' to retrieve the forth column's content expect(row.find(TableColumn).at(3).prop('content')).to.exist; // Using first and text to retrieve the columns text content expect(row.find(TableColumn).first().text()).to.eql('First column'); // Simulating events const button = shallow(<MyButton />); button.simulate('click'); expect(button.state('myActionWasPerformed')).to.be.true;
  • 16. Enzyme - Full DOM rendering mount(node[, options]) => ReactWrapper *More info at http://airbnb.io/enzyme/docs/api/mount.html Use it when interacting with DOM or testing full lifecycle (componentDidMount). it('calls componentDidMount', function() { spy(Foo.prototype, 'componentDidMount'); const wrapper = mount(<Foo />); expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true); }); it('allows us to set props', function() { const wrapper = mount(<Foo bar='baz' />); expect(wrapper.prop('bar')).to.equal('baz'); wrapper.setProps({ bar: 'foo' }); expect(wrapper.props('bar')).to.equal('foo'); }); Requires a full DOM API available at the global scope.
  • 17. Enzyme - Static rendered markup render(node[, options]) => CheerioWrapper *More info at http://airbnb.io/enzyme/docs/api/render.html Use it to render react components into static HTML (Uses Cheerio library). it('renders three .foo-bar', function() { const wrapper = render(<Foo />); expect(wrapper.find('.foo-bar')).to.have.length(3); }); it('rendered the title', function() { const wrapper = render(<Foo title="unique" />); expect(wrapper.text()).to.contain("unique"); });
  • 19. Simpsons Wheel - General overview App generateRandInfo(<value>) type: GENERATE_RANDINFO payload: { value: 1, timestamp: 1234} Reducers STATE randInfo: { value: 1, timestamp: 1234 } Wheel Button
  • 20. Simpsons Wheel - Component details (1 of 2) App component Renders Wheel component, passing items prop Renders Button component, passing max prop Button component Receives a max prop When clicked, computes a random value between 1 and max Calls action creator with the random number
  • 21. Simpsons Wheel - Component details (2 of 2) Wheel component Renders the images Stores the carousel rotation in its state Listens to Redux state changes Updates the rotation when receives new props
  • 22. Thanks for your time! Do you have any questions?