SlideShare uma empresa Scribd logo
1 de 60
Baixar para ler offline
We Are All 

Testers Now: 

The Testing Pyramid
and Front-End
Development
Van Wilson
@vanwilson
“A good presentation follows a story…”
— John Papa,
The Art of Public Speaking and Effective Presentations
This story is about
software quality
Things that Increase
Code Quality
Hiring competent employees
Providing employee training
Empowering employees to make decisions
Code reviews
Continuous Integration (short feedback loops)
Test-Driven Development
If you’ve looked at testing before…
Most material about developers writing tests
falls into one of two categories.
“Here’s how to test a function that add two
numbers. Now you can test anything. Good
luck.”
“You really should not be mocking your flux
capacitor, but instead link the flibitz to the
your cross-channel bit splicer.”
Definition of Test-Driven
Development
Write a test for the next bit of functionality
you want to add.
Write the functional code until the test passes.
Refactor both new and old code to make it
well structured.
- Martin Fowler, “TestDrivenDevelopment”, 

https://martinfowler.com/bliki/TestDrivenDevelopment.html
1. Write Tests
2. Run Test (TEST FAILS)
3. Write Code to Make
the Test to Pass
4. Run Test (TEST PASS)
5. Refactor 

(MAKE CODE CLEANER AND
FASTER)
6. Repeat
FAIL
PASSREFACTOR
Benefits of TDD
1. Writing tests first really helps you avoid a lot of bad
designs. 

It makes you think about the code you need to write,
BEFORE you write it.
2. Once you have tests, they help you avoid introducing
subtle bugs when you have to change the code later. 

Existing tests help prevent regressions in your code,
where adding or changing one thing accidentally
breaks another thing.
But if these two things are
true,
why doesn’t every developer
write tests first, all the time?
Exercising
Gives you more energy and other immediate
health benefits.
Helps you live longer, and with better quality of
life, down the road.
Saving money
Gives you a better credit rating, and an
emergency reserve, in the short term.
Allows you to retire earlier, and do more things
in retirement, in the future.
Flossing
Helps prevent cavities and gum disease now.
Helps you keep your teeth when you get older.
Let’s assume writing tests
first has those benefits…
… how do you get
started, and how do
you keep going?
Getting started with
any testing really is
the hardest part…
and JavaScript testing
is no exception.
Only slightly less
difficult, keeping
up with testing…
1. Management mandates
Test-Driven Development
2. Developers TDD all the
new things (YEAH! TESTS!)
3. Velocity slows because
TDD does take more time
up-front
4. “We’re not going to meet
this deadline ?!?” 

(STOP DOING TDD)
5. As tests age, skip them or
ignore failing tests

(PEOPLE IGNORE TESTS)
Start TDD
Deadlines
?!?
Graveyard
of

Tests
The Testing
Pyramid
Can’t we just tests everything with functional tests?
With end-to-end tests, you have to wait: first for the entire
product to be built, then for it to be deployed, and finally
for all end-to-end tests to run. When the tests do run, flaky
tests tend to be a fact of life. And even if a test finds a bug,
that bug could be anywhere in the product.
Although end-to-end tests do a better job of simulating real
user scenarios, this advantage quickly becomes outweighed
by all the disadvantages of the end-to-end feedback loop.
— https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html
Unit vs. Functional Tests
Anatomy of Any Test
Given - setup the environment
When - act on the System Under Test
(SUT) in that environment
Then - test what happened
Testing Library Fatigue
Jest
•Based on Jasmine
•Built-in assertions
•Built-in spies
For Unit / Integration Tests
Cucumber JS
•JS implementation of
Cucumber library
•Behavior-Driven
Development
•Runs on top of
Selenium
For Functional Tests
An example: TodoMVC
http://todomvc.com/examples/vanillajs/
TodoMVC example code
(function (window) {
'use strict';
function Model(storage) {
this.storage = storage;
}
Model.prototype.create = function
(title, callback) {
…
window.app = window.app || {};
window.app.Model = Model;
})(window);
Todos-with-TDD
http://todos-with-tdd.surge.sh/
Code at https://github.com/vjwilson/todos-with-tdd
Get started with

unit tests
3 Parts of Every Test
Arrange

“Given a number 10, and another
number 2”
Act

“When I raise the first number to the
power of the second number, 102
Assert

“I get 100 as an answer”
Testing a pure function
it('should return a singular string when
passed count of 1', function() {
// arrange
// set some variable
// act
// call some function
// assert
//
});
Given a certain value, it always returns the same value
Testing a pure function
it('should return a singular string when
passed count of 1', function() {
// arrange
var numActiveTodos = 1;
var template = new Template();
// …
});
An example from our Template module, part 1
Testing a pure function
it('should return a singular string when
passed count of 1', function() {
// …
// act
var counterView =
template.itemCounter(numActiveTodos);
// …
});
An example from our Template module, part 2
Testing a pure function
it('should return a singular string when
passed count of 1', function() {
// …
// assert
expect(counterView).toBe('<strong>1</
strong> item left');
});
An example from our Template module, part 3
Testing a pure function
it('should return a plural string when
passed count of more than 1',
function() {
var numActiveTodos = 2;
var template = new Template();
var counterView =
template.itemCounter(numActiveTodos);
expect(counterView).toBe('<strong>2</
strong> items left');
});
Testing the other path through the code
Testing a pure function
it('should return the correct grammar
when passed count of 0', function() {
var numActiveTodos = 0;
var template = new Template();
var counterView =
template.itemCounter(numActiveTodos);
expect(counterView).toBe('<strong>0</
strong> items left');
});
Testing an edge case
The building blocks of tests
test functions: 

test(), or it()
test suites: 

describe()
if you need to run the same setup for
multiple tests: 

beforeEach()
Jest matchers
Based on the popular Expect style of test matchers
• .toBeTruthy()
• .toBeFalsy()
• .toBeGreaterThan(number)
• .toBeGreaterThanOrEqual(number)
• .toBeLessThan(number)
• .toBeLessThanOrEqual(number)
• .toContain(item)
• .toEqual(value)

• .toHaveLength(number)
• .toMatch(regexpOrString)
• .toMatchObject(object)
• .toHaveProperty(keyPath, value)
• .toHaveBeenCalled()
• .toHaveBeenCalledTimes(number)
• .toHaveBeenCalledWith(arg1, …)
• … and many more
Testing side effects
it('should instantiate a store',
function() {
// arrange
// set some variable
// act
// call some function
// assert
?
});
Function interacts with API or the DOM
Peek at the global 🙈
it('should make a store in localStorage',
function() {
var storageName = 'shaggy';
var storage = new Store(storageName);
var dataStore =
JSON.parse(localStorage.getItem(stora
geName));
expect(typeof
dataStore).toEqual('object');
});
If you don’t have a return value, you’ve
got to find something else to test
Here’s where having a test-driven mindset
encourages you to have a more modular
architecture.
Callbacks/promises
Mocking: jest.fn()
Testing a callback
it('should call the given callback when
instantiated', function() {
var storageName = 'scooby';
var callback = jest.fn();
var storage = new Store(storageName,
callback);
var dataStoreShape = { todos: [] };
expect(callback).toHaveBeenCalledWith(

dataStoreShape);
});
Testing a function with dependencies
it('should get counts by item status',
function() {
var exampleTodos = [{…}, {…}, {…}];
var mockStore = {
findAll: jest.fn().mockImplementation(

function(callback) {
callback.call(null, exampleTodos);
})
};
…
});
Option 1, Using a mock
Testing a function with dependencies
it('should get counts by item status',
function() {
…
var model = new Model(mockStore);
var getCountCallback = jest.fn();
model.getCount(getCountCallback);
var expectedResult = { active: 2,
completed: 1, total: 3 };
expect(getCountCallback).toHaveBeenCall
edWith(expectedResult);
});
Option 1, Using a mock (continued)
On to
Integration Tests
Testing a function with dependencies
it('should get counts by item status',
function() {
var Store = require('../Store/Store.js');
var exampleTodos = [{…}, {…}, {…}];
var realStore = new Store(‘yamato');
exampleTodos.forEach(function(todo) {
realStore.save(todo)
});
…
});
Option 2, Just use the dependency
Testing a function with dependencies
it('should get counts by item status',
function() {
…
var model = new Model(realStore);
var getCountCallback = jest.fn();
model.getCount(getCountCallback);
var expectedResult = { active: 2,
completed: 1, total: 3 };
expect(getCountCallback).toHaveBeenCall
edWith(expectedResult);
});
Option 2, Just use the dependency (continued)
Top off with
functional tests
# add libraries
npm install --save-dev chromedriver cucumber selenium-webdriver
# add support file
touch features/support/world.js
# add hooks file
touch features/step_definitions/hooks.js
# add feature file
touch features/documentation.feature
# add step definitions
touch features/step_definitions/browser_steps.js
Setting up Cucumber JS
https://github.com/cucumber/cucumber-js
Example of functional testing
todo_input.feature
Feature: Todo input feature
As a user of Todos with TDD
I want to be able to enter a new todo item
So that I can add to my list of things to do
Scenario: See the todo input
Given I am on the Todos with TDD page
When I look for an element with class "new-todo"
Then I should see a placeholder of "What needs to be done?"
Scenario: Enter a new todo
Given I am on the Todos with TDD page
When I look for an element with class "new-todo"
And I enter text in the input field
Then I should see my new item in the Todo list
Testing the Cucumber.js site
var seleniumWebdriver = require('selenium-webdriver');
var {defineSupportCode} = require('cucumber');
var assert = require('assert');
defineSupportCode(function({Given, When, Then}) {
var todoInput;
Given('I am on the Todos with TDD page', function() {
return this.driver.get('http://localhost:8080');
});
…
todo_input_steps.js (part 1)
Testing the Cucumber.js site
…
When('I look for an element with class {string}', function
(className) {
return this.driver.findElement({ className:
className }).then(function(element) {
todoInput = element;
return element;
});
});
Then('I should see a placeholder of {string}', function
(expectedPlaceholder) {
return 

todoInput.getAttribute('placeholder').then(

function(placeholder) {
assert.equal(placeholder, expectedPlaceholder);
});
});
});
todo_input_steps.js (part 2)
Is it possible to apply test-driven development
principles with snapshot testing?

Although it is possible to write snapshot files
manually, that is usually not approachable.
Snapshots help figuring out whether the output of the
modules covered by tests is changed, rather than
giving guidance to design the code in the first place.
— https://facebook.github.io/jest/docs/snapshot-testing.html
A Note about Snapshot Testing
Resources
http://jrsinclair.com/articles/2016/
gentle-introduction-to-javascript-tdd-
intro/
https://facebook.github.io/jest/
More about functional
testing with JS
“Cucumber.js”, https://github.com/cucumber/
cucumber-js
“End to End testing of React apps with Nightwatch”,

https://blog.syncano.io/testing-syncano/
“Intern”, https://github.com/theintern/intern (a new
framework for managing unit and functional tests,
thanks to Jaydeep Parmar, @jaydeep98a, for this
reference)
Any questions?
Finis

Mais conteúdo relacionado

Mais procurados

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Yevgeniy Brikman
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Roberto Franchini
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma Christopher Bartling
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascriptEldar Djafarov
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersNaresha K
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance testBryan Liu
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontendFrederic CABASSUT
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissAndres Almiray
 
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
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaAndrey Kolodnitsky
 

Mais procurados (20)

Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)Node.js vs Play Framework (with Japanese subtitles)
Node.js vs Play Framework (with Japanese subtitles)
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
node.js practical guide to serverside javascript
node.js practical guide to serverside javascriptnode.js practical guide to serverside javascript
node.js practical guide to serverside javascript
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Automated acceptance test
Automated acceptance testAutomated acceptance test
Automated acceptance test
 
Everything as a code
Everything as a codeEverything as a code
Everything as a code
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Testing javascript in the frontend
Testing javascript in the frontendTesting javascript in the frontend
Testing javascript in the frontend
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to MissJava Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
 
Nodejs vatsal shah
Nodejs vatsal shahNodejs vatsal shah
Nodejs vatsal shah
 
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
 
Unit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and KarmaUnit testing in JavaScript with Jasmine and Karma
Unit testing in JavaScript with Jasmine and Karma
 

Semelhante a We Are All Testers Now: The Testing Pyramid and Front-End Development

Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLSteven Feuerstein
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It'sJim Lynch
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Knowvilniusjug
 
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
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnitAktuğ Urun
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Dror Helper
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdfHans Jones
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)vilniusjug
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciollaAndrea Paciolla
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slidesericholscher
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialAnup Singh
 
Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionDenard Springle IV
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 

Semelhante a We Are All Testers Now: The Testing Pyramid and Front-End Development (20)

Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
utPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQLutPLSQL: Unit Testing for Oracle PL/SQL
utPLSQL: Unit Testing for Oracle PL/SQL
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
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
 
Java Unit Test - JUnit
Java Unit Test - JUnitJava Unit Test - JUnit
Java Unit Test - JUnit
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Unit testing 101
Unit testing 101Unit testing 101
Unit testing 101
 
Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)Developer Tests - Things to Know (Vilnius JUG)
Developer Tests - Things to Know (Vilnius JUG)
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Token Testing Slides
Token  Testing SlidesToken  Testing Slides
Token Testing Slides
 
Test Driven
Test DrivenTest Driven
Test Driven
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Testing And Mxunit In ColdFusion
Testing And Mxunit In ColdFusionTesting And Mxunit In ColdFusion
Testing And Mxunit In ColdFusion
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 

Mais de All Things Open

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityAll Things Open
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best PracticesAll Things Open
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public PolicyAll Things Open
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...All Things Open
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashAll Things Open
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptAll Things Open
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?All Things Open
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractAll Things Open
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlowAll Things Open
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and SuccessAll Things Open
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with BackgroundAll Things Open
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblyAll Things Open
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksAll Things Open
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptAll Things Open
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramAll Things Open
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceAll Things Open
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamAll Things Open
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in controlAll Things Open
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsAll Things Open
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...All Things Open
 

Mais de All Things Open (20)

Building Reliability - The Realities of Observability
Building Reliability - The Realities of ObservabilityBuilding Reliability - The Realities of Observability
Building Reliability - The Realities of Observability
 
Modern Database Best Practices
Modern Database Best PracticesModern Database Best Practices
Modern Database Best Practices
 
Open Source and Public Policy
Open Source and Public PolicyOpen Source and Public Policy
Open Source and Public Policy
 
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
Weaving Microservices into a Unified GraphQL Schema with graph-quilt - Ashpak...
 
The State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil NashThe State of Passwordless Auth on the Web - Phil Nash
The State of Passwordless Auth on the Web - Phil Nash
 
Total ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScriptTotal ReDoS: The dangers of regex in JavaScript
Total ReDoS: The dangers of regex in JavaScript
 
What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?What Does Real World Mass Adoption of Decentralized Tech Look Like?
What Does Real World Mass Adoption of Decentralized Tech Look Like?
 
How to Write & Deploy a Smart Contract
How to Write & Deploy a Smart ContractHow to Write & Deploy a Smart Contract
How to Write & Deploy a Smart Contract
 
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
Spinning Your Drones with Cadence Workflows, Apache Kafka and TensorFlow
 
DEI Challenges and Success
DEI Challenges and SuccessDEI Challenges and Success
DEI Challenges and Success
 
Scaling Web Applications with Background
Scaling Web Applications with BackgroundScaling Web Applications with Background
Scaling Web Applications with Background
 
Supercharging tutorials with WebAssembly
Supercharging tutorials with WebAssemblySupercharging tutorials with WebAssembly
Supercharging tutorials with WebAssembly
 
Using SQL to Find Needles in Haystacks
Using SQL to Find Needles in HaystacksUsing SQL to Find Needles in Haystacks
Using SQL to Find Needles in Haystacks
 
Configuration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit InterceptConfiguration Security as a Game of Pursuit Intercept
Configuration Security as a Game of Pursuit Intercept
 
Scaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship ProgramScaling an Open Source Sponsorship Program
Scaling an Open Source Sponsorship Program
 
Build Developer Experience Teams for Open Source
Build Developer Experience Teams for Open SourceBuild Developer Experience Teams for Open Source
Build Developer Experience Teams for Open Source
 
Deploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache BeamDeploying Models at Scale with Apache Beam
Deploying Models at Scale with Apache Beam
 
Sudo – Giving access while staying in control
Sudo – Giving access while staying in controlSudo – Giving access while staying in control
Sudo – Giving access while staying in control
 
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML ApplicationsFortifying the Future: Tackling Security Challenges in AI/ML Applications
Fortifying the Future: Tackling Security Challenges in AI/ML Applications
 
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
Securing Cloud Resources Deployed with Control Planes on Kubernetes using Gov...
 

Último

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Último (20)

The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

We Are All Testers Now: The Testing Pyramid and Front-End Development

  • 1. We Are All 
 Testers Now: 
 The Testing Pyramid and Front-End Development Van Wilson @vanwilson
  • 2. “A good presentation follows a story…” — John Papa, The Art of Public Speaking and Effective Presentations
  • 3. This story is about software quality
  • 4. Things that Increase Code Quality Hiring competent employees Providing employee training Empowering employees to make decisions Code reviews Continuous Integration (short feedback loops) Test-Driven Development
  • 5. If you’ve looked at testing before… Most material about developers writing tests falls into one of two categories. “Here’s how to test a function that add two numbers. Now you can test anything. Good luck.” “You really should not be mocking your flux capacitor, but instead link the flibitz to the your cross-channel bit splicer.”
  • 6. Definition of Test-Driven Development Write a test for the next bit of functionality you want to add. Write the functional code until the test passes. Refactor both new and old code to make it well structured. - Martin Fowler, “TestDrivenDevelopment”, 
 https://martinfowler.com/bliki/TestDrivenDevelopment.html
  • 7. 1. Write Tests 2. Run Test (TEST FAILS) 3. Write Code to Make the Test to Pass 4. Run Test (TEST PASS) 5. Refactor 
 (MAKE CODE CLEANER AND FASTER) 6. Repeat FAIL PASSREFACTOR
  • 8. Benefits of TDD 1. Writing tests first really helps you avoid a lot of bad designs. 
 It makes you think about the code you need to write, BEFORE you write it. 2. Once you have tests, they help you avoid introducing subtle bugs when you have to change the code later. 
 Existing tests help prevent regressions in your code, where adding or changing one thing accidentally breaks another thing.
  • 9. But if these two things are true, why doesn’t every developer write tests first, all the time?
  • 10. Exercising Gives you more energy and other immediate health benefits. Helps you live longer, and with better quality of life, down the road.
  • 11. Saving money Gives you a better credit rating, and an emergency reserve, in the short term. Allows you to retire earlier, and do more things in retirement, in the future.
  • 12. Flossing Helps prevent cavities and gum disease now. Helps you keep your teeth when you get older.
  • 13. Let’s assume writing tests first has those benefits… … how do you get started, and how do you keep going?
  • 14. Getting started with any testing really is the hardest part… and JavaScript testing is no exception.
  • 15. Only slightly less difficult, keeping up with testing…
  • 16. 1. Management mandates Test-Driven Development 2. Developers TDD all the new things (YEAH! TESTS!) 3. Velocity slows because TDD does take more time up-front 4. “We’re not going to meet this deadline ?!?” 
 (STOP DOING TDD) 5. As tests age, skip them or ignore failing tests
 (PEOPLE IGNORE TESTS) Start TDD Deadlines ?!? Graveyard of
 Tests
  • 18.
  • 19.
  • 20.
  • 21. Can’t we just tests everything with functional tests? With end-to-end tests, you have to wait: first for the entire product to be built, then for it to be deployed, and finally for all end-to-end tests to run. When the tests do run, flaky tests tend to be a fact of life. And even if a test finds a bug, that bug could be anywhere in the product. Although end-to-end tests do a better job of simulating real user scenarios, this advantage quickly becomes outweighed by all the disadvantages of the end-to-end feedback loop. — https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html Unit vs. Functional Tests
  • 22. Anatomy of Any Test Given - setup the environment When - act on the System Under Test (SUT) in that environment Then - test what happened
  • 24. Jest •Based on Jasmine •Built-in assertions •Built-in spies For Unit / Integration Tests
  • 25. Cucumber JS •JS implementation of Cucumber library •Behavior-Driven Development •Runs on top of Selenium For Functional Tests
  • 27. TodoMVC example code (function (window) { 'use strict'; function Model(storage) { this.storage = storage; } Model.prototype.create = function (title, callback) { … window.app = window.app || {}; window.app.Model = Model; })(window);
  • 30.
  • 31. 3 Parts of Every Test Arrange
 “Given a number 10, and another number 2” Act
 “When I raise the first number to the power of the second number, 102 Assert
 “I get 100 as an answer”
  • 32. Testing a pure function it('should return a singular string when passed count of 1', function() { // arrange // set some variable // act // call some function // assert // }); Given a certain value, it always returns the same value
  • 33. Testing a pure function it('should return a singular string when passed count of 1', function() { // arrange var numActiveTodos = 1; var template = new Template(); // … }); An example from our Template module, part 1
  • 34. Testing a pure function it('should return a singular string when passed count of 1', function() { // … // act var counterView = template.itemCounter(numActiveTodos); // … }); An example from our Template module, part 2
  • 35. Testing a pure function it('should return a singular string when passed count of 1', function() { // … // assert expect(counterView).toBe('<strong>1</ strong> item left'); }); An example from our Template module, part 3
  • 36. Testing a pure function it('should return a plural string when passed count of more than 1', function() { var numActiveTodos = 2; var template = new Template(); var counterView = template.itemCounter(numActiveTodos); expect(counterView).toBe('<strong>2</ strong> items left'); }); Testing the other path through the code
  • 37. Testing a pure function it('should return the correct grammar when passed count of 0', function() { var numActiveTodos = 0; var template = new Template(); var counterView = template.itemCounter(numActiveTodos); expect(counterView).toBe('<strong>0</ strong> items left'); }); Testing an edge case
  • 38. The building blocks of tests test functions: 
 test(), or it() test suites: 
 describe() if you need to run the same setup for multiple tests: 
 beforeEach()
  • 39. Jest matchers Based on the popular Expect style of test matchers • .toBeTruthy() • .toBeFalsy() • .toBeGreaterThan(number) • .toBeGreaterThanOrEqual(number) • .toBeLessThan(number) • .toBeLessThanOrEqual(number) • .toContain(item) • .toEqual(value)
 • .toHaveLength(number) • .toMatch(regexpOrString) • .toMatchObject(object) • .toHaveProperty(keyPath, value) • .toHaveBeenCalled() • .toHaveBeenCalledTimes(number) • .toHaveBeenCalledWith(arg1, …) • … and many more
  • 40. Testing side effects it('should instantiate a store', function() { // arrange // set some variable // act // call some function // assert ? }); Function interacts with API or the DOM
  • 41. Peek at the global 🙈 it('should make a store in localStorage', function() { var storageName = 'shaggy'; var storage = new Store(storageName); var dataStore = JSON.parse(localStorage.getItem(stora geName)); expect(typeof dataStore).toEqual('object'); });
  • 42. If you don’t have a return value, you’ve got to find something else to test Here’s where having a test-driven mindset encourages you to have a more modular architecture. Callbacks/promises Mocking: jest.fn()
  • 43. Testing a callback it('should call the given callback when instantiated', function() { var storageName = 'scooby'; var callback = jest.fn(); var storage = new Store(storageName, callback); var dataStoreShape = { todos: [] }; expect(callback).toHaveBeenCalledWith(
 dataStoreShape); });
  • 44. Testing a function with dependencies it('should get counts by item status', function() { var exampleTodos = [{…}, {…}, {…}]; var mockStore = { findAll: jest.fn().mockImplementation(
 function(callback) { callback.call(null, exampleTodos); }) }; … }); Option 1, Using a mock
  • 45. Testing a function with dependencies it('should get counts by item status', function() { … var model = new Model(mockStore); var getCountCallback = jest.fn(); model.getCount(getCountCallback); var expectedResult = { active: 2, completed: 1, total: 3 }; expect(getCountCallback).toHaveBeenCall edWith(expectedResult); }); Option 1, Using a mock (continued)
  • 47.
  • 48. Testing a function with dependencies it('should get counts by item status', function() { var Store = require('../Store/Store.js'); var exampleTodos = [{…}, {…}, {…}]; var realStore = new Store(‘yamato'); exampleTodos.forEach(function(todo) { realStore.save(todo) }); … }); Option 2, Just use the dependency
  • 49. Testing a function with dependencies it('should get counts by item status', function() { … var model = new Model(realStore); var getCountCallback = jest.fn(); model.getCount(getCountCallback); var expectedResult = { active: 2, completed: 1, total: 3 }; expect(getCountCallback).toHaveBeenCall edWith(expectedResult); }); Option 2, Just use the dependency (continued)
  • 51.
  • 52. # add libraries npm install --save-dev chromedriver cucumber selenium-webdriver # add support file touch features/support/world.js # add hooks file touch features/step_definitions/hooks.js # add feature file touch features/documentation.feature # add step definitions touch features/step_definitions/browser_steps.js Setting up Cucumber JS https://github.com/cucumber/cucumber-js
  • 53. Example of functional testing todo_input.feature Feature: Todo input feature As a user of Todos with TDD I want to be able to enter a new todo item So that I can add to my list of things to do Scenario: See the todo input Given I am on the Todos with TDD page When I look for an element with class "new-todo" Then I should see a placeholder of "What needs to be done?" Scenario: Enter a new todo Given I am on the Todos with TDD page When I look for an element with class "new-todo" And I enter text in the input field Then I should see my new item in the Todo list
  • 54. Testing the Cucumber.js site var seleniumWebdriver = require('selenium-webdriver'); var {defineSupportCode} = require('cucumber'); var assert = require('assert'); defineSupportCode(function({Given, When, Then}) { var todoInput; Given('I am on the Todos with TDD page', function() { return this.driver.get('http://localhost:8080'); }); … todo_input_steps.js (part 1)
  • 55. Testing the Cucumber.js site … When('I look for an element with class {string}', function (className) { return this.driver.findElement({ className: className }).then(function(element) { todoInput = element; return element; }); }); Then('I should see a placeholder of {string}', function (expectedPlaceholder) { return 
 todoInput.getAttribute('placeholder').then(
 function(placeholder) { assert.equal(placeholder, expectedPlaceholder); }); }); }); todo_input_steps.js (part 2)
  • 56. Is it possible to apply test-driven development principles with snapshot testing?
 Although it is possible to write snapshot files manually, that is usually not approachable. Snapshots help figuring out whether the output of the modules covered by tests is changed, rather than giving guidance to design the code in the first place. — https://facebook.github.io/jest/docs/snapshot-testing.html A Note about Snapshot Testing
  • 58. More about functional testing with JS “Cucumber.js”, https://github.com/cucumber/ cucumber-js “End to End testing of React apps with Nightwatch”,
 https://blog.syncano.io/testing-syncano/ “Intern”, https://github.com/theintern/intern (a new framework for managing unit and functional tests, thanks to Jaydeep Parmar, @jaydeep98a, for this reference)
  • 60. Finis