SlideShare a Scribd company logo
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

What's hot

Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering
 
Workshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux Middleware
Visual Engineering
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
Ignacio Martín
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
Natasha Murashev
 
Reactive, component 그리고 angular2
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
Natasha Murashev
 
Practical Protocol-Oriented-Programming
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
Natasha Murashev
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
Visual Engineering
 
Protocol-Oriented MVVM
Protocol-Oriented MVVMProtocol-Oriented MVVM
Protocol-Oriented MVVM
Natasha Murashev
 
«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf
 
Workshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJSWorkshop 8: Templating: Handlebars, DustJS
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Workshop 3: JavaScript build tools
Workshop 3: JavaScript build toolsWorkshop 3: JavaScript build tools
Workshop 3: JavaScript build tools
Visual Engineering
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
Nir Kaufman
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
Christoffer Noring
 
Building scalable applications with angular js
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
Andrew Alpert
 
React Native One Day
React Native One DayReact Native One Day
React Native One Day
Troy Miles
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
Mihail Gaberov
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini
 

What's hot (20)

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

Similar to Workshop 23: ReactJS, React & Redux testing

Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
Jintin Lin
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
shadabgilani
 
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 testingAnna Khabibullina
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
Ihsan Fauzi Rahman
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
Suman Sourav
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
StephieJohn
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
Andrea Paciolla
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo2011
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
Artur Szott
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
John Congdon
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
DayNightGaMiNg
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
Knoldus Inc.
 

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

Annotation Processing
Annotation ProcessingAnnotation Processing
Annotation Processing
 
Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
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
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
Nevermore Unit Testing
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit Testing
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Release with confidence
Release with confidenceRelease with confidence
Release with confidence
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
Unit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
 

More from Visual Engineering

Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
Workshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
Visual Engineering
 
Workshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
Visual Engineering
 
Workshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - Structures
Visual Engineering
 
Workhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de Swift
Visual Engineering
 
Workshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux Advanced
Visual Engineering
 
Workshop 21: React Router
Workshop 21: React RouterWorkshop 21: React Router
Workshop 21: React Router
Visual Engineering
 
Workshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
Visual Engineering
 
Workshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte IWorkshop 16: EmberJS Parte I
Workshop 16: EmberJS Parte I
Visual Engineering
 
Workshop 15: Ionic framework
Workshop 15: Ionic frameworkWorkshop 15: Ionic framework
Workshop 15: Ionic framework
Visual Engineering
 
Workshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototyping
Visual Engineering
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
Visual Engineering
 
Workshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVCWorkshop 9: BackboneJS y patrones MVC
Workshop 9: BackboneJS y patrones MVC
Visual Engineering
 
Workshop 7: Single Page Applications
Workshop 7: Single Page ApplicationsWorkshop 7: Single Page Applications
Workshop 7: Single Page Applications
Visual Engineering
 
Workshop 6: Designer tools
Workshop 6: Designer toolsWorkshop 6: Designer tools
Workshop 6: Designer tools
Visual Engineering
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Workshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design PatternsWorkshop 2: JavaScript Design Patterns
Workshop 2: JavaScript Design Patterns
Visual Engineering
 

More from Visual Engineering (17)

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

Recently uploaded

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 

Recently uploaded (20)

GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 

Workshop 23: ReactJS, React & Redux testing

  • 1. Front End Workshops React Testing Cristina Hernández García chernandez@visual-engin.com Mario García Martín mgarcia@visual-engin.com
  • 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?