SlideShare ist ein Scribd-Unternehmen logo
1 von 72
Downloaden Sie, um offline zu lesen
Holger Grosse-Plankermann
Jest: Frontend Testing done right
Who am I?
Developer/Consultant/Whatever
Taming the Web since the 2000
Compiled Mozilla for bonus features
Backend vs. Frontend dev
Podcaster http://autoweird.fm
Holger Grosse-Plankermann
@holgergp
http://github.com/holgergp
Show of hands
Do you test your frontend code?
•Unit Testing
•Selenium/Test Cafe etc.
•HP Quality Center etc
•Macros
4
Show of hands
What test framework are you using?
•Jest
•Mocha
•Karma
5
•Jasmine
•Qunit
•Something else?
AGENDA
What is Jest
Why another library?
(Unit-) Tests in JavaScript
Where do I come from?
Where are we heading?
Top 3 reasons for Jest
Why I think Jest is awesome!
7
Where do I come from
(Unit-) Testing JS
Test Pyramid
E2E Test
Unit Test
Integration Test
Backend Test Pyramid
E2E Test
Unit Test
Integration Test
Frontend Test Pyramid
Unit Test
E2E-Test
Integration Test
Frontend Test Pyramid
E2E-Test
Integration Test
Unit Test
•Backend (Java) testing is well
established
•The important stuff is in the backend!
Some enterprise architect
•Need for unit testing
•And tooling is quite nice tbh
•mvn clean install ftw
In the backend
In the frontend
•Frontend (JS) testing used to be an
afterthought
•Less (underrated!) complexity
•Nah! We don’t need to test that
The same enterprise architect
•Messy tooling
•Tons of config and dependencies
needed to be orchestrated
•And that rumor is still in our heads
•In the age of SPAs
•More code than in the past
•Complex code
•Frontend code in itself is complex
•Also: Compared to backends
•Need for testing is already there
•Selenium is not enough!
Proper Testing in the frontend is important
Two sided test pyramid
E2E Test
Unit Test
Integration Test
Unit Test
Integration Test
Frontend Backend
14
A library that puts the fun in testing
Enter Jest
Delightful JavaScript Testing
http://jestjs.io/
•Testing library/framework
•node based
•Comparable to
•JUnit (Java)
•NUnit (.NET)
•Test::Unit (Ruby)
•PHPUnit (PHP)
What is Jest?
•Developed by Facebook
•Current version 23
•MIT licensed
•> 18.000 Github Stars
•Has been around since 2014
Jest: Facts and figures
Jest: Facts and figures
•Comes from Facebook but it’s not limited to React
•Works like a charm in my projects
•React based
•Vue based
•https://github.com/vuejs/vue-jest
•JQuery backed
•Angular
•https://github.com/thymikee/jest-preset-angular
Easy Setup
You can start with
very little config
Awesome CLI
A really polished
product
All in the box
Little to no need for
third party libs
Why I like Jest
19
Simple to install and simple to use
Easy setup
Create-React-App
Probably the easiest way to get going is
to just use create-react-app.
repl.it
Use an online repl might be even easier.
npm install jest
Come on, let’s get our hands dirty!
Let’s get started
I want to write the first test!
Be amazed
Install dependencies $ npm install -D jest
Let’s get started
package.json
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
Write a simple test
describe('Demo should', () => {
it('be green', () => {
expect(true).toBe(true);
});
});
Run it $> npm test
PASS ./demo.spec.js
Demo should
✓ be green (2ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.606s
Ran all test suites.
Anatomy of a test
describe("add", () => {
beforeEach(() => {})
afterEach(() => {})
beforeAll(() => {})
afterAll(() => {})
it("should compute the sum", () => {
expect(add(1, 2)).toBe(3);
});
});
test("should compute the sum", () => {
expect(add(1, 2)).toBe(3);
})
This gives a nice descriptive scoped
structure of your test.
As a bonus, Jest can print the
results nicely,
I can recommend that structure.
A more traditional way of writing
your tests. Possible, but less
expressive than the describe style.
Best practice: Nested blocks
•Use nesting of describe blocks to group your tests logically
•Setup code can be fine tuned for specific case
•Setup in nested describe
describe('Customer', () => {
beforeEach(() => {});
describe('placeOrder should', () => {
beforeEach(() => {});
it('be valid', () => {
expect(customer.placeOrder()).toBe(true);
});
});
describe('checkQty should', () => {
beforeEach(() => {});
it('be valid', () => {
expect(customer.checkQty()).toBe(1);
});
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Useful shortcuts
fdescribe()/describe.only()
fit()/it.only()
ftest()/test.only()
Executes only this block (in the block)
Skips the block
xdescribe()/describe.skip()
xit()/it.skip()
xtest()/test.skip()
Where are my tests?
•Out of the box, Jest looks for
__tests__/*
bar.spec.js
foo.test.js
•Configurable
•Suited my needs well thus far
Best practice: Code and Test nearby
•Makes it way easier to navigate between code and test
•Unusual at first, but grow fond of it
add.js
add.spec.js
mockable.js
mockable.spec.js
objectProducer.js
objectProducer.spec.js
stringProducer.js
stringProducer.spec.js
src/myApp
There is more
•Works with ES6
•With Babel
•Compile to JS friendly
•e.g. works (now) well with TypeScript
•All presets are configurable
•package.json
•CLI
•JS
Test runner trivia
•Jest runs
•tests in parallel
•tests in a sandbox
•No conflicting of tests
•failed tests first
Runs in your CI Server
I work with it in:
•Travis
•Gitlab CI
•Jenkins
28
Fun to work with
Awesome CLI
PASS client/service/skippingAndForcing.spec.js
PASS client/service/customMatchers.spec.js
PASS client/service/asymetricExpectations.spec.js
PASS client/service/serviceUser.spec.js
PASS client/service/newExpectations.spec.js
PASS client/service/httpServiceWithPromises.spec.js
PASS client/components/FirstTest.spec.js
PASS client/components/TextComponent.spec.jsx
PASS client/components/App.spec.jsx (5.539s)
PASS client/components/ListComponent.spec.jsx (5.589s)
Test Suites: 10 passed, 10 total
Tests: 5 skipped, 23 passed, 28 total
Snapshots: 5 passed, 5 total
Time: 9.83s
Ran all test suites.
Test results
•Nice output out of the box
FAIL ./add.spec.js
● add › should compute the sum
expect(received).toBe(expected) // Object.is equality
Expected value to be:
4
Received:
3
8 |
9 | it('should compute the sum', () => {
> 10 | expect(add(1, 2)).toBe(4);
11 | });
12 | });
13 |
at Object.<anonymous> (add.spec.js:10:27)
PASS ./asymetricExpectations.spec.js
..
Test Suites: 1 failed, 8 passed, 9 total
Tests: 1 failed, 5 skipped, 15 passed, 21 total
Meaningful error reports
Watch mode
•Looks for changes in the background
•Executes test automatically
•And more!
•Start via:
$ jest --watch
Watch mode Demo
Watch mode Demo
Watch mode Demo
Watch mode Demo
Watch mode Demo
Best practice: Watch mode on
•You get very fast feedback
•Nice for TDD
•Immersive
•One less task to do manually
•Make it a habit
Code coverage
$ jest --coverage
PASS client/service/newExpectations.spec.js
Ran all test suites.
-----------------------------|----------|----------|----------|----------|----------------|
File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines |
-----------------------------|----------|----------|----------|----------|----------------|
All files | 90.91 | 100 | 86.67 | 93.33 | |
components | 100 | 100 | 100 | 100 | |
App.jsx | 100 | 100 | 100 | 100 | |
ListComponent.jsx | 100 | 100 | 100 | 100 | |
TextComponent.jsx | 100 | 100 | 100 | 100 | |
service | 81.25 | 100 | 77.78 | 84.62 | |
httpService.js | 100 | 100 | 100 | 100 | |
httpServiceWithPromises.js | 100 | 100 | 100 | 100 | |
serviceUser.js | 62.5 | 100 | 50 | 66.67 | 9,10 |
-----------------------------|----------|----------|----------|----------|----------------|
•Computes coverage out of the box
Best practice: Coverage is your friend
•Sane default out of the box
•I use it regularly to see, where some test love may be needed
•Don’t go overboard with the numbers
•Use it as a guideline
•CI is a good place to make this visible
$ jest --verbose
PASS client/components/App.spec.jsx
App
✓ renders (14ms)
✓ calling Service correctly (3ms)
PASS client/service/httpServiceWithPromises.spec.js
httpService getPosts should
✓ talk to the backend using done (1ms)
✓ talk to the backend using promise returns
✓ talk to the backend using async await (1ms)
httpService getPostsRejecting should
✓ reject using done
✓ reject using expectations
✓ reject using async await (1ms)
Test Suites: 10 passed, 10 total
Tests: 5 skipped, 23 passed, 28 total
Snapshots: 5 passed, 5 total
Time: 2.187s
Ran all test suites.
Even nicer output
•verbose option
IDE Support
It just works
•I use it mainly in IntelliJ/Webstorm and it just works
•Use a Run Config like any other test
•Works fine in VSCode
•Some more config
•Not as polished as IntelliJ
•But fine for me
•I use the Jest extension
•I often use it on the command line
•Alongside the IDE
•The watch feature shines there
3
Less need for 3rd party libs
Batteries included
Expectations
Mocking
Snapshot Tests
What’s in the box
Async Tests
DOM Testing
Code coverage
Expectations .toBe(value)
.toHaveBeenCalled()
.toBeCloseTo(number, numDigits)
.toBeDefined()
.toBeFalsy()
.toBeGreaterThan(number)
.toBeGreaterThanOrEqual(number)
.toBeLessThan(number)
.toBeLessThanOrEqual(number)
.toBeInstanceOf(Class)
.toBeNull()
.toBeTruthy()
.toBeUndefined()
.toContain(item)
.toContainEqual(item)
.toEqual(value)
.toHaveLength(number)
.toMatch(regexpOrString)
.toMatchObject(object)
…
•No need for separate Mocha/Jasmine/expect
•All the expectations you need
•Matchers are extendable
https://facebook.github.io/jest/docs/en/expect.html
Expectations: Examples
Expecting Objects
1 describe('createCustomer should’, () => {
2 it('produce a valid customer',() => {
3 const customer = {name: 'Peter', premium: true};
4 expect(customer).toBeDefined();
5 expect(customer.name).toEqual('Peter');
6 expect(customer.name).toEqual(expect.stringContaining('ete'));
7 expect(customer).toEqual(expect.objectContaining({premium: true}));
8 })
9 });
Expecting Arrays
describe('createCustomers should', () => {
it('work with many customer',() => {
const customers = [
{name: 'Peter', premium: true},
{name: 'Max', premium: false},
{name: 'Tine', premium: true}
];
expect(customers).toContainEqual({name: 'Tine', premium: true});
})
});
1
2
3
4
5
6
7
8
9
1
0
Best practice: Few expectations
•Don’t go overboard with the expectations in the it blocks
•In doubt write one more it block
•Expectations following a failing expect don’t execute
Mocking
In a unit test it is often unfeasible to kickstart your whole dependency graph
Mocking lets you narrow down the scope of your test
{
}{
}
Mocking
•No need for separate Sinon.js
•Works similar to Mockito in Java
Mock Functions
Lets you replace more
complex logic with logic right
for your test
Manual Mocks
Lets you replace whole
modules for your test
Mock functions
describe('placeOrder should', () =>
it('order an available product', () => {
const product = {
isAvailable: jest.fn().mockReturnValue(true),
order: jest.fn()
};
placeOrder(product, 2, 'SOMMER');
expect(product.order).toHaveBeenCalled();
expect(product.order).toHaveBeenCalledTimes(1);
expect(product.order).lastCalledWith(2);
expect(product.order).toHaveBeenCalledWith(2);
})
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export function placeOrder(product, qty, seasonId) {
if (product.isAvailable(seasonId)) {
product.order(qty);
}
}
1
2
3
4
5
Manual mocks
import {processOrders} from './orderProcessor';
jest.mock('./3rdParty/orderRemoteService', () => {
const getOrdersFromRemote = () => ({
orders: [{id: 1, description: 'TestOrder1'},
{id: 2, description: 'TestOrder2'}]
});
return {
getOrdersFromRemote
};
});
describe('orderProcessor should', () => {
it('work with returned orders', () => {
expect(processOrders()).toEqual([1, 2]);
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { getOrdersFromRemote } from "./3rdParty/orderRemoteService";
export let processOrders = somePar => {
return getOrdersFromRemote().orders.map(it => it.id);
};
1
2
3
4
5
Best practice: Mock to reduce scope
•Use mocking if
•you set things up that don’t belong to your test
•you are only interested in the result (or an error!) of a dependency
•This makes the test more readable and potentially faster
•But beware if you see too much mocking involved
•Maybe your test can be smaller
•Maybe you need to restructure your dependencies
Snapshot tests
expect(validationMessage('Vorname')).toMatchSnapshot();
•Not (strictly) UI related!
•Jest stores result of function (i.e any serializable thing) to the fs the first run
•The stored thing is called Snapshot
exports[`validationMesssage should produce a valid message 1`] =
`"Feld 'Vorname' ist ein Pflichtfeld."`;
•Compares to this in consecutive test runs
expect(value).toMatchSnapshot()
Received value does not match stored snapshot 1.
- "Feld 'Vorname' ist ein Pflichtfeld."
+ "Das Feld 'Vorname' ist ein Pflichtfeld.“
› 1 snapshot test failed.
Test that would require some effort to expect
React components (that should not change)
Things you would not test otherwise
Best practice: Use Cases for
snapshot tests
Snapshot test may be brittle
You NEED to review your snapshot changes
No jest -u fire and forget
Prefer unit tests
Best practice: Caveats of snapshot
tests
it("talk to the backend using done", done => {
getCustomers().then(data => {
expect(data).toEqual(TEST_RESPONSE);
done();
});
});
1
2
3
4
5
6
Async tests
•You’ll encounter async code quite frequently
•Testing using callback way still works well
•Known from Jasmine
Async tests
it("talk to the backend using promise returns", () => {
return getCustomers().then(data => {
expect(data).toEqual(TEST_RESPONSE);
});
});
1
2
3
4
5
•Return a promise
it("talk to the backend using expectations", () => {
expect(getCustomers()).resolves.toEqual(TEST_RESPONSE);
});
1
2
3
•Use a matcher to resolve the provided promise
it("talk to the backend using async await", async () => {
const customers = await getCustomers();
expect(customers).toEqual(TEST_RESPONSE);
});
1
2
3
4
•Use async/await
DOM testing
•Jest comes with JSDOM to support testing DOM.
•JSDOM simulates a DOM-enviroment.
it('show text on page', () => {
const text = document.querySelector('#myText').innerHTML;
expect(text).toEqual('Lorem');
});
1
2
3
4
const setupDOM = () => {
document.body.innerHTML =
'<div>' +
' <div id="myText">Lorem</div>' +
'</div>';
};
1
2
3
4
5
6
•In a test you can setup a mock structure of your sites markup
•Assert in the DOM
•Useful when in conjunction with e.g. JQuery
Best practice: Keep away from DOM
•As long as you can
•Tests will be slow and brittle
•If you must expect sth in the DOM, keep it brief
DOM testing (outlook)
Test the rendering of your React application:
Enzyme (http://airbnb.io/enzyme/)
Enzyme is a JavaScript Testing utility for React that makes it
easier to assert, manipulate, and traverse your React
Components' output.
Browser testing using Jest:
Puppeteer (https://github.com/GoogleChrome/puppeteer) and
its Jest integration (https://facebook.github.io/jest/docs/en/
puppeteer.html)
Puppeteer is a Node library which provides a high-level API to
control headless Chrome or Chromium over the DevTools
Protocol.
Expectations
Mocking
Snapshot Tests
What’s in the box
Async Tests
DOM Testing
Code Coverage
And more
53
Some closing words
Coming to an end
What we had to do
{
"presets": ["env"]
}
Install dependencies $ npm install -D jest
package.json
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
babel
//.babelrc
{
"presets": ["env"]
}
$ npm install -D babel-jest babel-core
babel-preset-env
Easy to use and setup
Powerful features set yet familiar
Polished product (even the CLI)
Try Jest yourself
http://jestjs.io/
Some links
Tryout Jest
Release Blog
http://jestjs.io/blog/
Curated Links
github.com/jest-community/awesome-jest
Sample Code
github.com/holgergp/jestStarter
START
TESTING
YOUR
JS
TODAY
Questions?
Our mission – to promote agile development, innovation
and technology – extends through everything we do.
codecentric AG
Hochstraße 11
42697 Solingen
E-Mail: info@codecentric.de
www.codecentric.de
Telefon: +49 (0) 212. 23 36 28 0

Telefax: +49 (0) 212.23 36 28 79

Address
Contact Info
Telephone
Stay connected
Thanks for listening!
Picture Links
•https://unsplash.com/photos/xA5QE8Gtaak
•https://unsplash.com/photos/Wiu3w-99tNg
•https://unsplash.com/photos/FQjmQgSoRyQ
•https://unsplash.com/photos/h1v8lkfDUu4
•https://unsplash.com/photos/58tOB36ZTnw
•https://unsplash.com/photos/cEUl-0DSM9s
•https://unsplash.com/photos/9HI8UJMSdZA
•https://unsplash.com/photos/xhWMi9wdQaE
•https://unsplash.com/photos/R6xx6fnvPT8
•https://unsplash.com/photos/Q6jX7BbPE38
•https://unsplash.com/photos/8xAA0f9yQnE
•https://unsplash.com/photos/0YbeoQOX89k
•https://unsplash.com/photos/D56TpVU8zng
•https://unsplash.com/photos/TyQ-0lPp6e4
•https://unsplash.com/photos/gdBXlLO53N4
•https://unsplash.com/photos/uAFjFsMS3YY

Weitere ähnliche Inhalte

Was ist angesagt?

Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JSMichael Haberman
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introductionNir Kaufman
 
Acceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvmAcceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvmChristopher Bartling
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application TestingYnon Perek
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Deutsche Post
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraRuby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraBindesh Vijayan
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testingMats Bryntse
 
Javascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and GulpJavascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and GulpAll Things Open
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016Gavin Pickin
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Samyak Bhalerao
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017Ortus Solutions, Corp
 
CommandBox & ForgeBox Package Management
CommandBox & ForgeBox Package ManagementCommandBox & ForgeBox Package Management
CommandBox & ForgeBox Package ManagementOrtus Solutions, Corp
 
Jellyfish, JSCONF 2011
Jellyfish, JSCONF 2011Jellyfish, JSCONF 2011
Jellyfish, JSCONF 2011Adam Christian
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION APIGavin Pickin
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumDev9Com
 
Lunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraLunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraMarc Seeger
 

Was ist angesagt? (20)

Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introductionAngularjs - Unit testing introduction
Angularjs - Unit testing introduction
 
Acceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvmAcceptance Test-driven Development with Cucumber-jvm
Acceptance Test-driven Development with Cucumber-jvm
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
 
Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)Javascript Test Automation Workshop (21.08.2014)
Javascript Test Automation Workshop (21.08.2014)
 
Ruby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybaraRuby onrails cucumber-rspec-capybara
Ruby onrails cucumber-rspec-capybara
 
Java script unit testing
Java script unit testingJava script unit testing
Java script unit testing
 
Javascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and GulpJavascript TDD with Jasmine, Karma, and Gulp
Javascript TDD with Jasmine, Karma, and Gulp
 
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
How do I write Testable Javascript - Presented at dev.Objective() June 16, 2016
 
Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...Unit testing of java script and angularjs application using Karma Jasmine Fra...
Unit testing of java script and angularjs application using Karma Jasmine Fra...
 
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
North Virginia Coldfusion User Group Meetup - Testbox - July 19th 2017
 
CommandBox & ForgeBox Package Management
CommandBox & ForgeBox Package ManagementCommandBox & ForgeBox Package Management
CommandBox & ForgeBox Package Management
 
Jellyfish, JSCONF 2011
Jellyfish, JSCONF 2011Jellyfish, JSCONF 2011
Jellyfish, JSCONF 2011
 
3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API3 WAYS TO TEST YOUR COLDFUSION API
3 WAYS TO TEST YOUR COLDFUSION API
 
Automated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and SeleniumAutomated Testing with Cucumber, PhantomJS and Selenium
Automated Testing with Cucumber, PhantomJS and Selenium
 
Protractor training
Protractor trainingProtractor training
Protractor training
 
Automate Thyself
Automate ThyselfAutomate Thyself
Automate Thyself
 
Lunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and CapybaraLunch and learn: Cucumber and Capybara
Lunch and learn: Cucumber and Capybara
 

Ähnlich wie Das Frontend richtig Testen – mit Jest @Developer Week 2018

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 Howsatesgoral
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014Alex Kavanagh
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineGil Fink
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchMats Bryntse
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jskiyanwang
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passageErik Rose
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF SummitOrtus Solutions, Corp
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfullyTEST Huddle
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
Puppet Development Workflow
Puppet Development WorkflowPuppet Development Workflow
Puppet Development WorkflowJeffery Smith
 
Beyond TDD: Enabling Your Team to Continuously Deliver Software
Beyond TDD: Enabling Your Team to Continuously Deliver SoftwareBeyond TDD: Enabling Your Team to Continuously Deliver Software
Beyond TDD: Enabling Your Team to Continuously Deliver SoftwareChris Weldon
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonIneke Scheffers
 
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 Suiteericholscher
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptxTamas Rev
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1Yi-Huan Chan
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Jimmy Lu
 
Automated interactive testing for i os
Automated interactive testing for i osAutomated interactive testing for i os
Automated interactive testing for i osMobile March
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in nodeGoa App
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIwajrcs
 

Ähnlich wie Das Frontend richtig Testen – mit Jest @Developer Week 2018 (20)

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
 
TDD super mondays-june-2014
TDD super mondays-june-2014TDD super mondays-june-2014
TDD super mondays-june-2014
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Testing Ext JS and Sencha Touch
Testing Ext JS and Sencha TouchTesting Ext JS and Sencha Touch
Testing Ext JS and Sencha Touch
 
Node.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.jsNode.js Development Workflow Automation with Grunt.js
Node.js Development Workflow Automation with Grunt.js
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
3 Ways to test your ColdFusion API - 2017 Adobe CF Summit
 
How to use selenium successfully
How to use selenium successfullyHow to use selenium successfully
How to use selenium successfully
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
Puppet Development Workflow
Puppet Development WorkflowPuppet Development Workflow
Puppet Development Workflow
 
Beyond TDD: Enabling Your Team to Continuously Deliver Software
Beyond TDD: Enabling Your Team to Continuously Deliver SoftwareBeyond TDD: Enabling Your Team to Continuously Deliver Software
Beyond TDD: Enabling Your Team to Continuously Deliver Software
 
Developers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomonDevelopers Testing - Girl Code at bloomon
Developers Testing - Girl Code at bloomon
 
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
 
Surviving javascript.pptx
Surviving javascript.pptxSurviving javascript.pptx
Surviving javascript.pptx
 
Test in action – week 1
Test in action – week 1Test in action – week 1
Test in action – week 1
 
Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5Renaissance of JUnit - Introduction to JUnit 5
Renaissance of JUnit - Introduction to JUnit 5
 
Automated interactive testing for i os
Automated interactive testing for i osAutomated interactive testing for i os
Automated interactive testing for i os
 
unit test in node js - test cases in node
unit test in node js - test cases in nodeunit test in node js - test cases in node
unit test in node js - test cases in node
 
Continuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CIContinuous Delivery - Automate & Build Better Software with Travis CI
Continuous Delivery - Automate & Build Better Software with Travis CI
 

Kürzlich hochgeladen

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 

Kürzlich hochgeladen (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

Das Frontend richtig Testen – mit Jest @Developer Week 2018

  • 2. Who am I? Developer/Consultant/Whatever Taming the Web since the 2000 Compiled Mozilla for bonus features Backend vs. Frontend dev Podcaster http://autoweird.fm Holger Grosse-Plankermann @holgergp http://github.com/holgergp
  • 3. Show of hands Do you test your frontend code? •Unit Testing •Selenium/Test Cafe etc. •HP Quality Center etc •Macros 4
  • 4. Show of hands What test framework are you using? •Jest •Mocha •Karma 5 •Jasmine •Qunit •Something else?
  • 5. AGENDA What is Jest Why another library? (Unit-) Tests in JavaScript Where do I come from? Where are we heading? Top 3 reasons for Jest Why I think Jest is awesome!
  • 6. 7 Where do I come from (Unit-) Testing JS
  • 7. Test Pyramid E2E Test Unit Test Integration Test
  • 8. Backend Test Pyramid E2E Test Unit Test Integration Test
  • 9. Frontend Test Pyramid Unit Test E2E-Test Integration Test
  • 11. •Backend (Java) testing is well established •The important stuff is in the backend! Some enterprise architect •Need for unit testing •And tooling is quite nice tbh •mvn clean install ftw In the backend
  • 12. In the frontend •Frontend (JS) testing used to be an afterthought •Less (underrated!) complexity •Nah! We don’t need to test that The same enterprise architect •Messy tooling •Tons of config and dependencies needed to be orchestrated •And that rumor is still in our heads
  • 13. •In the age of SPAs •More code than in the past •Complex code •Frontend code in itself is complex •Also: Compared to backends •Need for testing is already there •Selenium is not enough! Proper Testing in the frontend is important
  • 14. Two sided test pyramid E2E Test Unit Test Integration Test Unit Test Integration Test Frontend Backend
  • 15. 14 A library that puts the fun in testing Enter Jest
  • 16. Delightful JavaScript Testing http://jestjs.io/ •Testing library/framework •node based •Comparable to •JUnit (Java) •NUnit (.NET) •Test::Unit (Ruby) •PHPUnit (PHP) What is Jest?
  • 17. •Developed by Facebook •Current version 23 •MIT licensed •> 18.000 Github Stars •Has been around since 2014 Jest: Facts and figures
  • 18. Jest: Facts and figures •Comes from Facebook but it’s not limited to React •Works like a charm in my projects •React based •Vue based •https://github.com/vuejs/vue-jest •JQuery backed •Angular •https://github.com/thymikee/jest-preset-angular
  • 19. Easy Setup You can start with very little config Awesome CLI A really polished product All in the box Little to no need for third party libs Why I like Jest
  • 20. 19 Simple to install and simple to use Easy setup
  • 21. Create-React-App Probably the easiest way to get going is to just use create-react-app. repl.it Use an online repl might be even easier. npm install jest Come on, let’s get our hands dirty! Let’s get started I want to write the first test!
  • 22. Be amazed Install dependencies $ npm install -D jest Let’s get started package.json "scripts": { "test": "jest", "test:watch": "jest --watch" } Write a simple test describe('Demo should', () => { it('be green', () => { expect(true).toBe(true); }); }); Run it $> npm test PASS ./demo.spec.js Demo should ✓ be green (2ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.606s Ran all test suites.
  • 23. Anatomy of a test describe("add", () => { beforeEach(() => {}) afterEach(() => {}) beforeAll(() => {}) afterAll(() => {}) it("should compute the sum", () => { expect(add(1, 2)).toBe(3); }); }); test("should compute the sum", () => { expect(add(1, 2)).toBe(3); }) This gives a nice descriptive scoped structure of your test. As a bonus, Jest can print the results nicely, I can recommend that structure. A more traditional way of writing your tests. Possible, but less expressive than the describe style.
  • 24. Best practice: Nested blocks •Use nesting of describe blocks to group your tests logically •Setup code can be fine tuned for specific case •Setup in nested describe describe('Customer', () => { beforeEach(() => {}); describe('placeOrder should', () => { beforeEach(() => {}); it('be valid', () => { expect(customer.placeOrder()).toBe(true); }); }); describe('checkQty should', () => { beforeEach(() => {}); it('be valid', () => { expect(customer.checkQty()).toBe(1); }); }); }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
  • 25. Useful shortcuts fdescribe()/describe.only() fit()/it.only() ftest()/test.only() Executes only this block (in the block) Skips the block xdescribe()/describe.skip() xit()/it.skip() xtest()/test.skip()
  • 26. Where are my tests? •Out of the box, Jest looks for __tests__/* bar.spec.js foo.test.js •Configurable •Suited my needs well thus far
  • 27. Best practice: Code and Test nearby •Makes it way easier to navigate between code and test •Unusual at first, but grow fond of it add.js add.spec.js mockable.js mockable.spec.js objectProducer.js objectProducer.spec.js stringProducer.js stringProducer.spec.js src/myApp
  • 28. There is more •Works with ES6 •With Babel •Compile to JS friendly •e.g. works (now) well with TypeScript •All presets are configurable •package.json •CLI •JS
  • 29. Test runner trivia •Jest runs •tests in parallel •tests in a sandbox •No conflicting of tests •failed tests first
  • 30. Runs in your CI Server I work with it in: •Travis •Gitlab CI •Jenkins
  • 31. 28 Fun to work with Awesome CLI
  • 32. PASS client/service/skippingAndForcing.spec.js PASS client/service/customMatchers.spec.js PASS client/service/asymetricExpectations.spec.js PASS client/service/serviceUser.spec.js PASS client/service/newExpectations.spec.js PASS client/service/httpServiceWithPromises.spec.js PASS client/components/FirstTest.spec.js PASS client/components/TextComponent.spec.jsx PASS client/components/App.spec.jsx (5.539s) PASS client/components/ListComponent.spec.jsx (5.589s) Test Suites: 10 passed, 10 total Tests: 5 skipped, 23 passed, 28 total Snapshots: 5 passed, 5 total Time: 9.83s Ran all test suites. Test results •Nice output out of the box
  • 33. FAIL ./add.spec.js ● add › should compute the sum expect(received).toBe(expected) // Object.is equality Expected value to be: 4 Received: 3 8 | 9 | it('should compute the sum', () => { > 10 | expect(add(1, 2)).toBe(4); 11 | }); 12 | }); 13 | at Object.<anonymous> (add.spec.js:10:27) PASS ./asymetricExpectations.spec.js .. Test Suites: 1 failed, 8 passed, 9 total Tests: 1 failed, 5 skipped, 15 passed, 21 total Meaningful error reports
  • 34. Watch mode •Looks for changes in the background •Executes test automatically •And more! •Start via: $ jest --watch
  • 40. Best practice: Watch mode on •You get very fast feedback •Nice for TDD •Immersive •One less task to do manually •Make it a habit
  • 41. Code coverage $ jest --coverage PASS client/service/newExpectations.spec.js Ran all test suites. -----------------------------|----------|----------|----------|----------|----------------| File | % Stmts | % Branch | % Funcs | % Lines |Uncovered Lines | -----------------------------|----------|----------|----------|----------|----------------| All files | 90.91 | 100 | 86.67 | 93.33 | | components | 100 | 100 | 100 | 100 | | App.jsx | 100 | 100 | 100 | 100 | | ListComponent.jsx | 100 | 100 | 100 | 100 | | TextComponent.jsx | 100 | 100 | 100 | 100 | | service | 81.25 | 100 | 77.78 | 84.62 | | httpService.js | 100 | 100 | 100 | 100 | | httpServiceWithPromises.js | 100 | 100 | 100 | 100 | | serviceUser.js | 62.5 | 100 | 50 | 66.67 | 9,10 | -----------------------------|----------|----------|----------|----------|----------------| •Computes coverage out of the box
  • 42. Best practice: Coverage is your friend •Sane default out of the box •I use it regularly to see, where some test love may be needed •Don’t go overboard with the numbers •Use it as a guideline •CI is a good place to make this visible
  • 43. $ jest --verbose PASS client/components/App.spec.jsx App ✓ renders (14ms) ✓ calling Service correctly (3ms) PASS client/service/httpServiceWithPromises.spec.js httpService getPosts should ✓ talk to the backend using done (1ms) ✓ talk to the backend using promise returns ✓ talk to the backend using async await (1ms) httpService getPostsRejecting should ✓ reject using done ✓ reject using expectations ✓ reject using async await (1ms) Test Suites: 10 passed, 10 total Tests: 5 skipped, 23 passed, 28 total Snapshots: 5 passed, 5 total Time: 2.187s Ran all test suites. Even nicer output •verbose option
  • 44. IDE Support It just works •I use it mainly in IntelliJ/Webstorm and it just works •Use a Run Config like any other test •Works fine in VSCode •Some more config •Not as polished as IntelliJ •But fine for me •I use the Jest extension •I often use it on the command line •Alongside the IDE •The watch feature shines there
  • 45. 3 Less need for 3rd party libs Batteries included
  • 46. Expectations Mocking Snapshot Tests What’s in the box Async Tests DOM Testing Code coverage
  • 48. Expectations: Examples Expecting Objects 1 describe('createCustomer should’, () => { 2 it('produce a valid customer',() => { 3 const customer = {name: 'Peter', premium: true}; 4 expect(customer).toBeDefined(); 5 expect(customer.name).toEqual('Peter'); 6 expect(customer.name).toEqual(expect.stringContaining('ete')); 7 expect(customer).toEqual(expect.objectContaining({premium: true})); 8 }) 9 }); Expecting Arrays describe('createCustomers should', () => { it('work with many customer',() => { const customers = [ {name: 'Peter', premium: true}, {name: 'Max', premium: false}, {name: 'Tine', premium: true} ]; expect(customers).toContainEqual({name: 'Tine', premium: true}); }) }); 1 2 3 4 5 6 7 8 9 1 0
  • 49. Best practice: Few expectations •Don’t go overboard with the expectations in the it blocks •In doubt write one more it block •Expectations following a failing expect don’t execute
  • 50. Mocking In a unit test it is often unfeasible to kickstart your whole dependency graph Mocking lets you narrow down the scope of your test { }{ }
  • 51. Mocking •No need for separate Sinon.js •Works similar to Mockito in Java Mock Functions Lets you replace more complex logic with logic right for your test Manual Mocks Lets you replace whole modules for your test
  • 52. Mock functions describe('placeOrder should', () => it('order an available product', () => { const product = { isAvailable: jest.fn().mockReturnValue(true), order: jest.fn() }; placeOrder(product, 2, 'SOMMER'); expect(product.order).toHaveBeenCalled(); expect(product.order).toHaveBeenCalledTimes(1); expect(product.order).lastCalledWith(2); expect(product.order).toHaveBeenCalledWith(2); }) ); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 export function placeOrder(product, qty, seasonId) { if (product.isAvailable(seasonId)) { product.order(qty); } } 1 2 3 4 5
  • 53. Manual mocks import {processOrders} from './orderProcessor'; jest.mock('./3rdParty/orderRemoteService', () => { const getOrdersFromRemote = () => ({ orders: [{id: 1, description: 'TestOrder1'}, {id: 2, description: 'TestOrder2'}] }); return { getOrdersFromRemote }; }); describe('orderProcessor should', () => { it('work with returned orders', () => { expect(processOrders()).toEqual([1, 2]); }); }); 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import { getOrdersFromRemote } from "./3rdParty/orderRemoteService"; export let processOrders = somePar => { return getOrdersFromRemote().orders.map(it => it.id); }; 1 2 3 4 5
  • 54. Best practice: Mock to reduce scope •Use mocking if •you set things up that don’t belong to your test •you are only interested in the result (or an error!) of a dependency •This makes the test more readable and potentially faster •But beware if you see too much mocking involved •Maybe your test can be smaller •Maybe you need to restructure your dependencies
  • 55. Snapshot tests expect(validationMessage('Vorname')).toMatchSnapshot(); •Not (strictly) UI related! •Jest stores result of function (i.e any serializable thing) to the fs the first run •The stored thing is called Snapshot exports[`validationMesssage should produce a valid message 1`] = `"Feld 'Vorname' ist ein Pflichtfeld."`; •Compares to this in consecutive test runs expect(value).toMatchSnapshot() Received value does not match stored snapshot 1. - "Feld 'Vorname' ist ein Pflichtfeld." + "Das Feld 'Vorname' ist ein Pflichtfeld.“ › 1 snapshot test failed.
  • 56. Test that would require some effort to expect React components (that should not change) Things you would not test otherwise Best practice: Use Cases for snapshot tests
  • 57. Snapshot test may be brittle You NEED to review your snapshot changes No jest -u fire and forget Prefer unit tests Best practice: Caveats of snapshot tests
  • 58. it("talk to the backend using done", done => { getCustomers().then(data => { expect(data).toEqual(TEST_RESPONSE); done(); }); }); 1 2 3 4 5 6 Async tests •You’ll encounter async code quite frequently •Testing using callback way still works well •Known from Jasmine
  • 59. Async tests it("talk to the backend using promise returns", () => { return getCustomers().then(data => { expect(data).toEqual(TEST_RESPONSE); }); }); 1 2 3 4 5 •Return a promise it("talk to the backend using expectations", () => { expect(getCustomers()).resolves.toEqual(TEST_RESPONSE); }); 1 2 3 •Use a matcher to resolve the provided promise it("talk to the backend using async await", async () => { const customers = await getCustomers(); expect(customers).toEqual(TEST_RESPONSE); }); 1 2 3 4 •Use async/await
  • 60. DOM testing •Jest comes with JSDOM to support testing DOM. •JSDOM simulates a DOM-enviroment. it('show text on page', () => { const text = document.querySelector('#myText').innerHTML; expect(text).toEqual('Lorem'); }); 1 2 3 4 const setupDOM = () => { document.body.innerHTML = '<div>' + ' <div id="myText">Lorem</div>' + '</div>'; }; 1 2 3 4 5 6 •In a test you can setup a mock structure of your sites markup •Assert in the DOM •Useful when in conjunction with e.g. JQuery
  • 61. Best practice: Keep away from DOM •As long as you can •Tests will be slow and brittle •If you must expect sth in the DOM, keep it brief
  • 62. DOM testing (outlook) Test the rendering of your React application: Enzyme (http://airbnb.io/enzyme/) Enzyme is a JavaScript Testing utility for React that makes it easier to assert, manipulate, and traverse your React Components' output. Browser testing using Jest: Puppeteer (https://github.com/GoogleChrome/puppeteer) and its Jest integration (https://facebook.github.io/jest/docs/en/ puppeteer.html) Puppeteer is a Node library which provides a high-level API to control headless Chrome or Chromium over the DevTools Protocol.
  • 63. Expectations Mocking Snapshot Tests What’s in the box Async Tests DOM Testing Code Coverage And more
  • 65. What we had to do { "presets": ["env"] } Install dependencies $ npm install -D jest package.json "scripts": { "test": "jest", "test:watch": "jest --watch" } babel //.babelrc { "presets": ["env"] } $ npm install -D babel-jest babel-core babel-preset-env
  • 66. Easy to use and setup Powerful features set yet familiar Polished product (even the CLI) Try Jest yourself
  • 67. http://jestjs.io/ Some links Tryout Jest Release Blog http://jestjs.io/blog/ Curated Links github.com/jest-community/awesome-jest Sample Code github.com/holgergp/jestStarter
  • 69.
  • 71. Our mission – to promote agile development, innovation and technology – extends through everything we do. codecentric AG Hochstraße 11 42697 Solingen E-Mail: info@codecentric.de www.codecentric.de Telefon: +49 (0) 212. 23 36 28 0
 Telefax: +49 (0) 212.23 36 28 79
 Address Contact Info Telephone Stay connected Thanks for listening!