Workshop 23: ReactJS, React & Redux testing

Visual Engineering
Visual EngineeringVisual Engineering
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
1 of 23

Recommended

Workshop 26: React Native - The Native Side by
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
2.8K views54 slides
Workshop 17: EmberJS parte II by
Workshop 17: EmberJS parte IIWorkshop 17: EmberJS parte II
Workshop 17: EmberJS parte IIVisual Engineering
856 views54 slides
Workshop 1: Good practices in JavaScript by
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptVisual Engineering
963 views45 slides
Workshop 25: React Native - Components by
Workshop 25: React Native - ComponentsWorkshop 25: React Native - Components
Workshop 25: React Native - ComponentsVisual Engineering
1.1K views21 slides
Workshop 14: AngularJS Parte III by
Workshop 14: AngularJS Parte IIIWorkshop 14: AngularJS Parte III
Workshop 14: AngularJS Parte IIIVisual Engineering
759 views54 slides
Workshop 24: React Native Introduction by
Workshop 24: React Native IntroductionWorkshop 24: React Native Introduction
Workshop 24: React Native IntroductionVisual Engineering
913 views15 slides

More Related Content

What's hot

Workshop 20: ReactJS Part II Flux Pattern & Redux by
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxVisual Engineering
1.2K views19 slides
Workshop 22: React-Redux Middleware by
Workshop 22: React-Redux MiddlewareWorkshop 22: React-Redux Middleware
Workshop 22: React-Redux MiddlewareVisual Engineering
2.3K views29 slides
Workshop 5: JavaScript testing by
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
823 views48 slides
Redux Sagas - React Alicante by
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
2.8K views128 slides
Protocol-Oriented MVVM (extended edition) by
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Natasha Murashev
5.2K views55 slides
Reactive, component 그리고 angular2 by
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2Jeado Ko
1.7K views71 slides

What's hot(20)

Workshop 20: ReactJS Part II Flux Pattern & Redux by Visual Engineering
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
Visual Engineering1.2K views
Protocol-Oriented MVVM (extended edition) by Natasha Murashev
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
Natasha Murashev5.2K views
Reactive, component 그리고 angular2 by Jeado Ko
Reactive, component 그리고  angular2Reactive, component 그리고  angular2
Reactive, component 그리고 angular2
Jeado Ko1.7K views
Practical Protocol-Oriented-Programming by Natasha Murashev
Practical Protocol-Oriented-ProgrammingPractical Protocol-Oriented-Programming
Practical Protocol-Oriented-Programming
Natasha Murashev90.3K views
«От экспериментов с инфраструктурой до внедрения в продакшен»​ by FDConf
«От экспериментов с инфраструктурой до внедрения в продакшен»​«От экспериментов с инфраструктурой до внедрения в продакшен»​
«От экспериментов с инфраструктурой до внедрения в продакшен»​
FDConf5.3K views
Using React, Redux and Saga with Lottoland APIs by Mihail Gaberov
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov1.2K views
How Angular2 Can Improve Your AngularJS Apps Today! by Nir Kaufman
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 Kaufman1.8K views
Building scalable applications with angular js by Andrew Alpert
Building scalable applications with angular jsBuilding scalable applications with angular js
Building scalable applications with angular js
Andrew Alpert13.4K views
React Native One Day by Troy Miles
React Native One DayReact Native One Day
React Native One Day
Troy Miles910 views
Async JavaScript Unit Testing by Mihail Gaberov
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
Mihail Gaberov161 views
Kotlin Delegates in practice - Kotlin community conf by Fabio Collini
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community conf
Fabio Collini123 views

Similar to Workshop 23: ReactJS, React & Redux testing

Annotation Processing by
Annotation ProcessingAnnotation Processing
Annotation ProcessingJintin Lin
134 views67 slides
Protractor framework architecture with example by
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with exampleshadabgilani
208 views21 slides
In search of JavaScript code quality: unit testing by
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testingAnna Khabibullina
1.2K views35 slides
Javascript unit testing, yes we can e big by
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
1.1K views35 slides
Nevermore Unit Testing by
Nevermore Unit TestingNevermore Unit Testing
Nevermore Unit TestingIhsan Fauzi Rahman
256 views12 slides
Junit_.pptx by
Junit_.pptxJunit_.pptx
Junit_.pptxSuman Sourav
18 views18 slides

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

Annotation Processing by Jintin Lin
Annotation ProcessingAnnotation Processing
Annotation Processing
Jintin Lin134 views
Protractor framework architecture with example by shadabgilani
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
shadabgilani208 views
In search of JavaScript code quality: unit testing by Anna Khabibullina
In search of JavaScript code quality: unit testingIn search of JavaScript code quality: unit testing
In search of JavaScript code quality: unit testing
Anna Khabibullina1.2K views
Javascript unit testing, yes we can e big by Andy Peterson
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
Andy Peterson1.1K views
Fundamental Concepts of React JS for Beginners.pdf by StephieJohn
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
StephieJohn110 views
JavaScript Growing Up by David Padbury
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury14.1K views
JavaScript Basics by Mats Bryntse
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse1.6K views
比XML更好用的Java Annotation by javatwo2011
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
javatwo20111K views
Grails unit testing by pleeps
Grails unit testingGrails unit testing
Grails unit testing
pleeps4.1K views
Adding a modern twist to legacy web applications by Jeff Durta
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta345 views
MeetJS Summit 2016: React.js enlightenment by Artur Szott
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
Artur Szott665 views
Bring the fun back to java by ciklum_ods
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods640 views
Release with confidence by John Congdon
Release with confidenceRelease with confidence
Release with confidence
John Congdon1.8K views
Build Web Apps using Node.js by davidchubbs
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
davidchubbs675 views
Unit Testing and Coverage for AngularJS by Knoldus Inc.
Unit Testing and Coverage for AngularJSUnit Testing and Coverage for AngularJS
Unit Testing and Coverage for AngularJS
Knoldus Inc.4.8K views

More from Visual Engineering

Workshop 27: Isomorphic web apps with ReactJS by
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
944 views26 slides
Workshop iOS 4: Closures, generics & operators by
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operatorsVisual Engineering
507 views7 slides
Workshop iOS 3: Testing, protocolos y extensiones by
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensionesVisual Engineering
695 views49 slides
Workshop iOS 2: Swift - Structures by
Workshop iOS 2: Swift - StructuresWorkshop iOS 2: Swift - Structures
Workshop iOS 2: Swift - StructuresVisual Engineering
553 views25 slides
Workhop iOS 1: Fundamentos de Swift by
Workhop iOS 1: Fundamentos de SwiftWorkhop iOS 1: Fundamentos de Swift
Workhop iOS 1: Fundamentos de SwiftVisual Engineering
486 views35 slides
Workshop 22: ReactJS Redux Advanced by
Workshop 22: ReactJS Redux AdvancedWorkshop 22: ReactJS Redux Advanced
Workshop 22: ReactJS Redux AdvancedVisual Engineering
1.3K views29 slides

More from Visual Engineering(17)

Workshop 27: Isomorphic web apps with ReactJS by Visual Engineering
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering944 views
Workshop iOS 4: Closures, generics & operators by Visual Engineering
Workshop iOS 4: Closures, generics & operatorsWorkshop iOS 4: Closures, generics & operators
Workshop iOS 4: Closures, generics & operators
Visual Engineering507 views
Workshop iOS 3: Testing, protocolos y extensiones by Visual Engineering
Workshop iOS 3: Testing, protocolos y extensionesWorkshop iOS 3: Testing, protocolos y extensiones
Workshop iOS 3: Testing, protocolos y extensiones
Visual Engineering695 views
Workshop 18: CSS Animations & cool effects by Visual Engineering
Workshop 18: CSS Animations & cool effectsWorkshop 18: CSS Animations & cool effects
Workshop 18: CSS Animations & cool effects
Visual Engineering1.2K views
Workshop 11: Trendy web designs & prototyping by Visual Engineering
Workshop 11: Trendy web designs & prototypingWorkshop 11: Trendy web designs & prototyping
Workshop 11: Trendy web designs & prototyping
Visual Engineering823 views
Workshop 4: NodeJS. Express Framework & MongoDB. by Visual Engineering
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering1.6K views

Recently uploaded

2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptxanimuscrm
13 views19 slides
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsRa'Fat Al-Msie'deen
5 views49 slides
Winter '24 Release Chat.pdf by
Winter '24 Release Chat.pdfWinter '24 Release Chat.pdf
Winter '24 Release Chat.pdfmelbourneauuser
9 views20 slides
El Arte de lo Possible by
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo PossibleNeo4j
38 views35 slides
HarshithAkkapelli_Presentation.pdf by
HarshithAkkapelli_Presentation.pdfHarshithAkkapelli_Presentation.pdf
HarshithAkkapelli_Presentation.pdfharshithakkapelli
11 views16 slides
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...Deltares
9 views26 slides

Recently uploaded(20)

2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm13 views
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports by Ra'Fat Al-Msie'deen
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug ReportsBushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
BushraDBR: An Automatic Approach to Retrieving Duplicate Bug Reports
El Arte de lo Possible by Neo4j
El Arte de lo PossibleEl Arte de lo Possible
El Arte de lo Possible
Neo4j38 views
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t... by Deltares
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
DSD-INT 2023 Thermobaricity in 3D DCSM-FM - taking pressure into account in t...
Deltares9 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor22 views
Advanced API Mocking Techniques by Dimpy Adhikary
Advanced API Mocking TechniquesAdvanced API Mocking Techniques
Advanced API Mocking Techniques
Dimpy Adhikary19 views
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ... by Deltares
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
Deltares9 views
Software evolution understanding: Automatic extraction of software identifier... by Ra'Fat Al-Msie'deen
Software evolution understanding: Automatic extraction of software identifier...Software evolution understanding: Automatic extraction of software identifier...
Software evolution understanding: Automatic extraction of software identifier...
DSD-INT 2023 HydroMT model building and river-coast coupling in Python - Bove... by Deltares
DSD-INT 2023 HydroMT model building and river-coast coupling in Python - Bove...DSD-INT 2023 HydroMT model building and river-coast coupling in Python - Bove...
DSD-INT 2023 HydroMT model building and river-coast coupling in Python - Bove...
Deltares17 views
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI... by Marc Müller
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Dev-Cloud Conference 2023 - Continuous Deployment Showdown: Traditionelles CI...
Marc Müller36 views
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon by Deltares
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - AfternoonDSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
Deltares13 views
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ... by marksimpsongw
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...
Mark Simpson - UKOUG23 - Refactoring Monolithic Oracle Database Applications ...
marksimpsongw76 views
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida by Deltares
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - PridaDSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
DSD-INT 2023 Dam break simulation in Derna (Libya) using HydroMT_SFINCS - Prida
Deltares18 views
DSD-INT 2023 FloodAdapt - A decision-support tool for compound flood risk mit... by Deltares
DSD-INT 2023 FloodAdapt - A decision-support tool for compound flood risk mit...DSD-INT 2023 FloodAdapt - A decision-support tool for compound flood risk mit...
DSD-INT 2023 FloodAdapt - A decision-support tool for compound flood risk mit...
Deltares13 views

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?