SlideShare une entreprise Scribd logo
1  sur  41
Télécharger pour lire hors ligne
1
JASMINEWhy JavaScript tests don’t smell fishy?
WHAT I WILL TALK ABOUT:
2
• What is Unit Testing
• Solution: Jasmine - whole syntax with examples
• WebStorm goodies
• Benefits of Units Tests
• Why people don’t test JavaScript?
• Test Driven Development, Behavior Driven Development
WHY PEOPLE DON’T TEST JAVASCRIPT ?
• project not big enough
• project too complex
• asynchronous XHR requests
• DOM manipulation
• too many browsers, platforms, devices
3
UNIT TESTING is a program (test case or test specification) that
isolates and tests small and specific functional unit of code.
Test one small functionality per suite. Not too many things at one time.
Remember! It impossible to write test for every case - try to cover every
reasonable case, remember about corner cases
4
GOOD PRACTICES
BENEFITS OF USING JAVASCRIPT TESTS
5
• QA phase is cheaper - you will uncover bugs earlier
• Creates great documentation
• As a developer you will write better code
• Shows that JS should work as was designed
• Quick and easy to run - try to do it with manual testing
• Runs the same every time
TDD & BDD
Behavior Driven Development: agile software development technique
testing from business value perspective, why some code is necessary
and what its goal is
6
Test Driven Development: write tests against specification, watch your
test fail, write some code, test, refactor, test-fix-implement
TDD vs BDD
Example: 10 sorting methods
TDD:
one test per one method - focused on „how” each method works
BDD:
one test per all methods - focused on the goal
give an array, sort, result
7
JASMINE MATCHERS - EQUALITY
expect(true).toEqual(true);
expect({}).toEqual({});
8
toEqual
JASMINE MATCHERS - IDENTITY
var spot = { species: "Border Collie" };
var cosmo = { species: "Border Collie" };
// success; equivalent
expect(spot).toEqual(cosmo);
// failure; not the same object
expect(spot).toBe(cosmo);
// success; the same value
expect(2).toBe(2);
toBe
checks if two things are the same
value and type, using ===
Primitive Types vs Reference Types
primitive will be give you true, reference will give you false
9
JASMINE MATCHERS - BOOLEAN
expect(true).toBeTruthy();
expect(12).toBeTruthy();
expect({}).toBeTruthy();
expect(false).toBeFalsy();
expect(null).toBeFalsy();
expect("").toBeFalsy();
//false, 0, “”, undefinded, null, NaN
toBeTruthy toBeFalsy10
JASMINE MATCHERS - NEGATION
expect(this).not.toEqual(that);
expect({}).not.toBe([]);
not11
JASMINE MATCHERS - CONTAINS
expect([1, 2, 3, 4]).toContain(3);
expect(["Jasmine", "Qunit", "Mocha", "Casper"]).toContain("Jasmine");
expect("Rychu Peja to pener").toContain("pener");
var dog = { name: "Reksio" };
expect([
{ name: "Dżeki" },
{ name: "Max" },
{ name: "Reksio" }
]).toContain(dog);
toContain12
JASMINE MATCHERS - DEFINED OR UNDEFINED
var somethingUndefined;
expect("Hello!").toBeDefined(); // success
expect(null).toBeDefined(); // success
expect(somethingUndefined).toBeDefined(); // failure
var somethingElseUndefined;
expect(somethingElseUndefined).toBeUndefined(); // success
expect(2013).toBeUndefined(); // failure
expect(null).toBeUndefined(); // failure
toBeDefined toBeUndefined13
JASMINE MATCHERS - NULLNESS
expect(null).toBeNull(); // success
expect(false).toBeNull(); // failure
expect(somethingUndefined).toBeNull(); // failure
//null is where the thing is known to exist,
//but it's not known what the value is.
toBeNull14
JASMINE MATCHERS - IS NaN
expect(5).not.toBeNaN(); // success
expect(0 / 0).toBeNaN(); // success
expect(parseInt("hello")).toBeNaN(); // success
/*
This is different from JavaScript’s built-in isNaN function. The
built-in isNaN will return true for many nonnumber types, such as
nonnumeric strings, objects, and arrays. Jasmine’s will be positive
only if it’s the NaN value.
*/
toBeNaN15
JASMINE MATCHERS - COMPARATORS
expect(8).toBeGreaterThan(5);
expect(5).toBeLessThan(12);
expect("a").toBeLessThan("z"); // it works for strings
toBeGreaterThan toBeLessThan16
JASMINE MATCHERS - NEARNESS
expect(12.34).toBeCloseTo(12.3, 1); // success
toBeCloseTo17
JASMINE MATCHERS - REGULAR EXPRESSIONS
expect("some words").toMatch(/some/); // success
toMatch18
JASMINE MATCHERS - ERROR THROWING
var errorThrower = function () {
throw new Error();
}
expect(errorThrower).toThrow(); // success
toThrow19
JASMINE - BEFORE AND AFTER TESTS
var player, wallet; // remember about scope
beforeEach( function () {
player = new Player;
});
afterEach( function () {
wallet.empty(); // empty after each test
});
beforeEach afterEach20
JASMINE MATCHERS - CUSTOM MATCHERS
beforeEach( function () {
this.addMatchers({
toBeLarge: function () {
this.message = function () {
return "Expected " + this.actual + " to be large";
};
return this.actual > 100;
}
});
});
expect(5).toBeLarge(); // failure
expect(101).toBeLarge(); // success
custom matchers21
JASMINE - NESTED SUITS
describe("Expected ", function () {
describe("something ", function () {
it("should do something", function () {
expect(2).toBe(2);
});
});
});
22
describe describe
JASMINE - SKIP THE TEST
describe("Expected ", function () {
xdescribe("something ", function () {
xit("should do something", function () {
expect(2).toBe(2);
});
return;
it("should do something else", function () {
expect(3).toBe(3);
});
});
});
23
xit xdescribe return
JASMINE - SPIES
var Dictionary = function() {},
Person = function() {};
Dictionary.prototype.hello = function () {
return "hello";
};
Dictionary.prototype.world = function () {
return "world";
};
Person.prototype.sayHelloWorld = function(dict) {
return dict.hello() + " " + dict.world();
};
var dictionary = new Dictionary,
person = new Person;
person.sayHelloWorld(dictionary); // returns "hello world"
describe("Person", function() {
it('uses the dict to say "hello world"', function() {
var dictionary = new Dictionary,
person = new Person;
// replace each function with a spy
spyOn(dictionary, "hello");
spyOn(dictionary, "world");
person.sayHelloWorld(dictionary);
// not possible without first spies
expect(dictionary.hello).toHaveBeenCalled();
expect(dictionary.world).toHaveBeenCalled();
});
});
toHaveBeenCalled
Often you test more than variable checks. Spy can pretend that he is a function or an object.
24
JASMINE - SPIES can call through the function
describe("Person", function() {
it('uses the dictionary to say "hello world"', function () {
var dictionary = new Dictionary,
person = new Person;
spyOn(person, "sayHelloWorld"); // replace hello world function with a spy
person.sayHelloWorld(dictionary);
expect(person.sayHelloWorld).toHaveBeenCalledWith(dictionary);
});
});
toHaveBeenCalledWith25
JASMINE - SPIES can return specific value
it("spy can return specific value", function () {
var dictionary = new Dictionary,
person = new Person,
result;
spyOn(dictionary, "hello").andReturn("Witaj");
result = person.sayHelloWorld(dictionary);
expect(result).toEqual("Witaj world");
});
andReturn26
JASMINE - SPIES can count its calls
callCount
it("can count calls of spy", function () {
var dictionary = new Dictionary,
spy;
spy = spyOn(dictionary, "hello");
dictionary.hello();
expect(spy.callCount).toEqual(1);
});
27
JASMINE - SPIES can get recent arguments
mostRecentCall.args
it("can give you last arguments", function () {
var dictionary = new Dictionary,
person = new Person,
spy;
spy = spyOn(person, "sayHelloWorld");
person.sayHelloWorld("No siemano");
// remember arguments will be in array
expect(spy.mostRecentCall.args).toEqual(["No siemano"]);
});
28
JASMINE - SPIES can get arguments of specific call
argsForCall[index]
it("can give you last arguments", function () {
var dictionary = new Dictionary,
person = new Person,
spy;
spy = spyOn(person, "sayHelloWorld");
person.sayHelloWorld("No siemano");
person.sayHelloWorld("Hejka");
// remember arguments will be in array and argForCall is also array
expect(spy.argsForCall[1]).toEqual(["Hejka"]);
});
29
JASMINE - SPIES can call fake functions
it("can call a fake function", function() {
var fakeHello = function() {
console.log("I’m a fake function");
return "hello";
};
var dictionary = new Dictionary();
spyOn(dictionary, "hello").andCallFake(fakeHello);
dictionary.hello(); // does an log
});
andCallFake30
JASMINE - SPIES can be created on its own
it("can have a spy function", function() {
var person = new Person();
person.getName = jasmine.createSpy("Name spy");
person.getName();
expect(person.getName).toHaveBeenCalled();
});
jasmine.createSpy31
32
JASMINE - SPIES can chain actions
person.getSecretAgentName = jasmine.createSpy("Name spy").andReturn("James Bond");
chaning
JASMINE - SPIES can be an object
it("spy can be an object", function() {
var player = jasmine.createSpyObj("player", ["hustle", "rap"]);
player.hustle();
// magic to test
});
jasmine.createSpyObj33
JASMINE - asynchronous - RUNS
it("runnin’", function() {
runs(function() {
it("should do something", function () {
expect(2).toBe(2);
});
});
});
runs34
JASMINE - asynchronous - WAITS
it('should be a test', function () {
runs(function () {
this.foo = 0;
var that = this;
setTimeout(function () {
that.foo++;
}, 250);
});
runs(function () {
expect(this.foo).toEqual(0);
});
waits(1000);
runs(function () {
expect(this.foo).toEqual(1);
});
});
waits35
36
JASMINE - asynchronous - WAITS FOR
describe('asynchronous wait for', function() {
it('should wait for something', function () {
var spreadsheet = new Spreadsheet();
waitsFor(function() {
return true; // here you can call your function which should be true
}, "Something went wrong", 3000);
runs(function () {
expect(2).toEqual(2);
});
});
});
waitsFor(function, opt message, opt timeout)
JASMINE - jQuery matchers
toBe(jQuerySelector)
toBeChecked()
toBeEmpty()
toBeHidden()
toHaveCss(css)
toBeSelected()
toBeVisible()
toContain(jQuerySelector)
toExist()
toHaveAttr(attributeName, attributeValue)
toHaveProp(propertyName, propertyValue)
toHaveBeenTriggeredOn(selector)
toHaveBeenTriggered()
toHaveBeenTriggeredOnAndWith(selector,
extraParameters)
toHaveBeenPreventedOn(selector)
toHaveBeenPrevented()
toHaveClass(className)
toHaveData(key, value)
toHaveHtml(string)
toContainHtml(string)
toContainText(string)
toHaveId(id)
toHaveText(string)
toHaveValue(value)
toHaveLength(value)
toBeDisabled()
toBeFocused()
toHandle(eventName)
toHandleWith(eventName, eventHandler)
37
JASMINE - HTML & JSON fixtures
//myfixture.html
<div id="my-fixture">some complex content here</div>
//some fixture adding
loadFixtures('myfixture.html');
$('#my-fixture').myTestedPlugin();
expect($('#my-fixture')).toBe('div');
38
JASMINE for AJAX
39
Sinon
Jasmine AJAX
Github Present for WebStorm users
40
https://github.com/thisisui/jetbrains-jasmine-test-startup
41
THANKS FOR YOUR TIME
QUESTIONS?

Contenu connexe

Tendances

Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express MiddlewareMorris Singer
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaChristopher Bartling
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
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
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.jsRotem Tamir
 
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
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Morris Singer
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmineTimothy Oxley
 
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
 
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
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsFITC
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasminefoxp2code
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript TestingThomas Fuchs
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
Testing JS with Jasmine
Testing JS with JasmineTesting JS with Jasmine
Testing JS with JasmineEvgeny Gurin
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSJim Lynch
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 

Tendances (20)

Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express Middleware
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Full Stack Unit Testing
Full Stack Unit TestingFull Stack Unit Testing
Full Stack Unit Testing
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
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
 
Unit tests in node.js
Unit tests in node.jsUnit tests in node.js
Unit tests in node.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
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Intro to testing Javascript with jasmine
Intro to testing Javascript with jasmineIntro to testing Javascript with jasmine
Intro to testing Javascript with jasmine
 
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
 
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
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
AngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and JasmineAngularJS Unit Testing w/Karma and Jasmine
AngularJS Unit Testing w/Karma and Jasmine
 
Adventures In JavaScript Testing
Adventures In JavaScript TestingAdventures In JavaScript Testing
Adventures In JavaScript Testing
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
Testing JS with Jasmine
Testing JS with JasmineTesting JS with Jasmine
Testing JS with Jasmine
 
Intro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJSIntro to Unit Testing in AngularJS
Intro to Unit Testing in AngularJS
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 

En vedette

Behavior Driven Development with AngularJS & Jasmine
Behavior Driven Development with AngularJS & JasmineBehavior Driven Development with AngularJS & Jasmine
Behavior Driven Development with AngularJS & JasmineRemus Langu
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptSumanth krishna
 
Applying BDD/TDD practices, using Jasmine.js
Applying BDD/TDD practices, using Jasmine.jsApplying BDD/TDD practices, using Jasmine.js
Applying BDD/TDD practices, using Jasmine.jsAnil Tarte
 
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)Dimitar Danailov
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit TestChiew Carol
 
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...Jasmine Sandler
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineAnup Singh
 
Behavior Driven Development (BDD) and Agile Testing
Behavior Driven Development (BDD) and Agile TestingBehavior Driven Development (BDD) and Agile Testing
Behavior Driven Development (BDD) and Agile Testingdversaci
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsWork at Play
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven DevelopmentLiz Keogh
 
Detangling Your JavaScript
Detangling Your JavaScriptDetangling Your JavaScript
Detangling Your JavaScriptChris Powers
 

En vedette (16)

Behavior Driven Development with AngularJS & Jasmine
Behavior Driven Development with AngularJS & JasmineBehavior Driven Development with AngularJS & Jasmine
Behavior Driven Development with AngularJS & Jasmine
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScript
 
Karma - JS Test Runner
Karma - JS Test RunnerKarma - JS Test Runner
Karma - JS Test Runner
 
Applying BDD/TDD practices, using Jasmine.js
Applying BDD/TDD practices, using Jasmine.jsApplying BDD/TDD practices, using Jasmine.js
Applying BDD/TDD practices, using Jasmine.js
 
BDD agile china2012_share
BDD agile china2012_shareBDD agile china2012_share
BDD agile china2012_share
 
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)
 
AngularJS Unit Test
AngularJS Unit TestAngularJS Unit Test
AngularJS Unit Test
 
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
jasmine
jasminejasmine
jasmine
 
Behavior Driven Development (BDD) and Agile Testing
Behavior Driven Development (BDD) and Agile TestingBehavior Driven Development (BDD) and Agile Testing
Behavior Driven Development (BDD) and Agile Testing
 
Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and Jenkins
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven Development
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Detangling Your JavaScript
Detangling Your JavaScriptDetangling Your JavaScript
Detangling Your JavaScript
 
Jasmine
JasmineJasmine
Jasmine
 

Similaire à Jasmine - why JS tests don't smell fishy

2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalQA or the Highway
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action scriptChristophe Herreman
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Colin Oakley
 
Javascript basics
Javascript basicsJavascript basics
Javascript basicsSolv AS
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
What's New in JavaScript
What's New in JavaScriptWhat's New in JavaScript
What's New in JavaScriptDan Cohn
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroAdam Crabtree
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.jsJay Harris
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talksjeresig
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays
 

Similaire à Jasmine - why JS tests don't smell fishy (20)

Introduccion a Jasmin
Introduccion a JasminIntroduccion a Jasmin
Introduccion a Jasmin
 
2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript2013-06-15 - Software Craftsmanship mit JavaScript
2013-06-15 - Software Craftsmanship mit JavaScript
 
2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript2013-06-24 - Software Craftsmanship with JavaScript
2013-06-24 - Software Craftsmanship with JavaScript
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Short intro to ECMAScript
Short intro to ECMAScriptShort intro to ECMAScript
Short intro to ECMAScript
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017Testing most things in JavaScript - LeedsJS 31/05/2017
Testing most things in JavaScript - LeedsJS 31/05/2017
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
What's New in JavaScript
What's New in JavaScriptWhat's New in JavaScript
What's New in JavaScript
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
LinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
 
Specs2
Specs2Specs2
Specs2
 
Shibuya.js Lightning Talks
Shibuya.js Lightning TalksShibuya.js Lightning Talks
Shibuya.js Lightning Talks
 
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6
 

Dernier

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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
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
 
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
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Dernier (20)

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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
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
 
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...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Jasmine - why JS tests don't smell fishy

  • 1. 1 JASMINEWhy JavaScript tests don’t smell fishy?
  • 2. WHAT I WILL TALK ABOUT: 2 • What is Unit Testing • Solution: Jasmine - whole syntax with examples • WebStorm goodies • Benefits of Units Tests • Why people don’t test JavaScript? • Test Driven Development, Behavior Driven Development
  • 3. WHY PEOPLE DON’T TEST JAVASCRIPT ? • project not big enough • project too complex • asynchronous XHR requests • DOM manipulation • too many browsers, platforms, devices 3
  • 4. UNIT TESTING is a program (test case or test specification) that isolates and tests small and specific functional unit of code. Test one small functionality per suite. Not too many things at one time. Remember! It impossible to write test for every case - try to cover every reasonable case, remember about corner cases 4 GOOD PRACTICES
  • 5. BENEFITS OF USING JAVASCRIPT TESTS 5 • QA phase is cheaper - you will uncover bugs earlier • Creates great documentation • As a developer you will write better code • Shows that JS should work as was designed • Quick and easy to run - try to do it with manual testing • Runs the same every time
  • 6. TDD & BDD Behavior Driven Development: agile software development technique testing from business value perspective, why some code is necessary and what its goal is 6 Test Driven Development: write tests against specification, watch your test fail, write some code, test, refactor, test-fix-implement
  • 7. TDD vs BDD Example: 10 sorting methods TDD: one test per one method - focused on „how” each method works BDD: one test per all methods - focused on the goal give an array, sort, result 7
  • 8. JASMINE MATCHERS - EQUALITY expect(true).toEqual(true); expect({}).toEqual({}); 8 toEqual
  • 9. JASMINE MATCHERS - IDENTITY var spot = { species: "Border Collie" }; var cosmo = { species: "Border Collie" }; // success; equivalent expect(spot).toEqual(cosmo); // failure; not the same object expect(spot).toBe(cosmo); // success; the same value expect(2).toBe(2); toBe checks if two things are the same value and type, using === Primitive Types vs Reference Types primitive will be give you true, reference will give you false 9
  • 10. JASMINE MATCHERS - BOOLEAN expect(true).toBeTruthy(); expect(12).toBeTruthy(); expect({}).toBeTruthy(); expect(false).toBeFalsy(); expect(null).toBeFalsy(); expect("").toBeFalsy(); //false, 0, “”, undefinded, null, NaN toBeTruthy toBeFalsy10
  • 11. JASMINE MATCHERS - NEGATION expect(this).not.toEqual(that); expect({}).not.toBe([]); not11
  • 12. JASMINE MATCHERS - CONTAINS expect([1, 2, 3, 4]).toContain(3); expect(["Jasmine", "Qunit", "Mocha", "Casper"]).toContain("Jasmine"); expect("Rychu Peja to pener").toContain("pener"); var dog = { name: "Reksio" }; expect([ { name: "Dżeki" }, { name: "Max" }, { name: "Reksio" } ]).toContain(dog); toContain12
  • 13. JASMINE MATCHERS - DEFINED OR UNDEFINED var somethingUndefined; expect("Hello!").toBeDefined(); // success expect(null).toBeDefined(); // success expect(somethingUndefined).toBeDefined(); // failure var somethingElseUndefined; expect(somethingElseUndefined).toBeUndefined(); // success expect(2013).toBeUndefined(); // failure expect(null).toBeUndefined(); // failure toBeDefined toBeUndefined13
  • 14. JASMINE MATCHERS - NULLNESS expect(null).toBeNull(); // success expect(false).toBeNull(); // failure expect(somethingUndefined).toBeNull(); // failure //null is where the thing is known to exist, //but it's not known what the value is. toBeNull14
  • 15. JASMINE MATCHERS - IS NaN expect(5).not.toBeNaN(); // success expect(0 / 0).toBeNaN(); // success expect(parseInt("hello")).toBeNaN(); // success /* This is different from JavaScript’s built-in isNaN function. The built-in isNaN will return true for many nonnumber types, such as nonnumeric strings, objects, and arrays. Jasmine’s will be positive only if it’s the NaN value. */ toBeNaN15
  • 16. JASMINE MATCHERS - COMPARATORS expect(8).toBeGreaterThan(5); expect(5).toBeLessThan(12); expect("a").toBeLessThan("z"); // it works for strings toBeGreaterThan toBeLessThan16
  • 17. JASMINE MATCHERS - NEARNESS expect(12.34).toBeCloseTo(12.3, 1); // success toBeCloseTo17
  • 18. JASMINE MATCHERS - REGULAR EXPRESSIONS expect("some words").toMatch(/some/); // success toMatch18
  • 19. JASMINE MATCHERS - ERROR THROWING var errorThrower = function () { throw new Error(); } expect(errorThrower).toThrow(); // success toThrow19
  • 20. JASMINE - BEFORE AND AFTER TESTS var player, wallet; // remember about scope beforeEach( function () { player = new Player; }); afterEach( function () { wallet.empty(); // empty after each test }); beforeEach afterEach20
  • 21. JASMINE MATCHERS - CUSTOM MATCHERS beforeEach( function () { this.addMatchers({ toBeLarge: function () { this.message = function () { return "Expected " + this.actual + " to be large"; }; return this.actual > 100; } }); }); expect(5).toBeLarge(); // failure expect(101).toBeLarge(); // success custom matchers21
  • 22. JASMINE - NESTED SUITS describe("Expected ", function () { describe("something ", function () { it("should do something", function () { expect(2).toBe(2); }); }); }); 22 describe describe
  • 23. JASMINE - SKIP THE TEST describe("Expected ", function () { xdescribe("something ", function () { xit("should do something", function () { expect(2).toBe(2); }); return; it("should do something else", function () { expect(3).toBe(3); }); }); }); 23 xit xdescribe return
  • 24. JASMINE - SPIES var Dictionary = function() {}, Person = function() {}; Dictionary.prototype.hello = function () { return "hello"; }; Dictionary.prototype.world = function () { return "world"; }; Person.prototype.sayHelloWorld = function(dict) { return dict.hello() + " " + dict.world(); }; var dictionary = new Dictionary, person = new Person; person.sayHelloWorld(dictionary); // returns "hello world" describe("Person", function() { it('uses the dict to say "hello world"', function() { var dictionary = new Dictionary, person = new Person; // replace each function with a spy spyOn(dictionary, "hello"); spyOn(dictionary, "world"); person.sayHelloWorld(dictionary); // not possible without first spies expect(dictionary.hello).toHaveBeenCalled(); expect(dictionary.world).toHaveBeenCalled(); }); }); toHaveBeenCalled Often you test more than variable checks. Spy can pretend that he is a function or an object. 24
  • 25. JASMINE - SPIES can call through the function describe("Person", function() { it('uses the dictionary to say "hello world"', function () { var dictionary = new Dictionary, person = new Person; spyOn(person, "sayHelloWorld"); // replace hello world function with a spy person.sayHelloWorld(dictionary); expect(person.sayHelloWorld).toHaveBeenCalledWith(dictionary); }); }); toHaveBeenCalledWith25
  • 26. JASMINE - SPIES can return specific value it("spy can return specific value", function () { var dictionary = new Dictionary, person = new Person, result; spyOn(dictionary, "hello").andReturn("Witaj"); result = person.sayHelloWorld(dictionary); expect(result).toEqual("Witaj world"); }); andReturn26
  • 27. JASMINE - SPIES can count its calls callCount it("can count calls of spy", function () { var dictionary = new Dictionary, spy; spy = spyOn(dictionary, "hello"); dictionary.hello(); expect(spy.callCount).toEqual(1); }); 27
  • 28. JASMINE - SPIES can get recent arguments mostRecentCall.args it("can give you last arguments", function () { var dictionary = new Dictionary, person = new Person, spy; spy = spyOn(person, "sayHelloWorld"); person.sayHelloWorld("No siemano"); // remember arguments will be in array expect(spy.mostRecentCall.args).toEqual(["No siemano"]); }); 28
  • 29. JASMINE - SPIES can get arguments of specific call argsForCall[index] it("can give you last arguments", function () { var dictionary = new Dictionary, person = new Person, spy; spy = spyOn(person, "sayHelloWorld"); person.sayHelloWorld("No siemano"); person.sayHelloWorld("Hejka"); // remember arguments will be in array and argForCall is also array expect(spy.argsForCall[1]).toEqual(["Hejka"]); }); 29
  • 30. JASMINE - SPIES can call fake functions it("can call a fake function", function() { var fakeHello = function() { console.log("I’m a fake function"); return "hello"; }; var dictionary = new Dictionary(); spyOn(dictionary, "hello").andCallFake(fakeHello); dictionary.hello(); // does an log }); andCallFake30
  • 31. JASMINE - SPIES can be created on its own it("can have a spy function", function() { var person = new Person(); person.getName = jasmine.createSpy("Name spy"); person.getName(); expect(person.getName).toHaveBeenCalled(); }); jasmine.createSpy31
  • 32. 32 JASMINE - SPIES can chain actions person.getSecretAgentName = jasmine.createSpy("Name spy").andReturn("James Bond"); chaning
  • 33. JASMINE - SPIES can be an object it("spy can be an object", function() { var player = jasmine.createSpyObj("player", ["hustle", "rap"]); player.hustle(); // magic to test }); jasmine.createSpyObj33
  • 34. JASMINE - asynchronous - RUNS it("runnin’", function() { runs(function() { it("should do something", function () { expect(2).toBe(2); }); }); }); runs34
  • 35. JASMINE - asynchronous - WAITS it('should be a test', function () { runs(function () { this.foo = 0; var that = this; setTimeout(function () { that.foo++; }, 250); }); runs(function () { expect(this.foo).toEqual(0); }); waits(1000); runs(function () { expect(this.foo).toEqual(1); }); }); waits35
  • 36. 36 JASMINE - asynchronous - WAITS FOR describe('asynchronous wait for', function() { it('should wait for something', function () { var spreadsheet = new Spreadsheet(); waitsFor(function() { return true; // here you can call your function which should be true }, "Something went wrong", 3000); runs(function () { expect(2).toEqual(2); }); }); }); waitsFor(function, opt message, opt timeout)
  • 37. JASMINE - jQuery matchers toBe(jQuerySelector) toBeChecked() toBeEmpty() toBeHidden() toHaveCss(css) toBeSelected() toBeVisible() toContain(jQuerySelector) toExist() toHaveAttr(attributeName, attributeValue) toHaveProp(propertyName, propertyValue) toHaveBeenTriggeredOn(selector) toHaveBeenTriggered() toHaveBeenTriggeredOnAndWith(selector, extraParameters) toHaveBeenPreventedOn(selector) toHaveBeenPrevented() toHaveClass(className) toHaveData(key, value) toHaveHtml(string) toContainHtml(string) toContainText(string) toHaveId(id) toHaveText(string) toHaveValue(value) toHaveLength(value) toBeDisabled() toBeFocused() toHandle(eventName) toHandleWith(eventName, eventHandler) 37
  • 38. JASMINE - HTML & JSON fixtures //myfixture.html <div id="my-fixture">some complex content here</div> //some fixture adding loadFixtures('myfixture.html'); $('#my-fixture').myTestedPlugin(); expect($('#my-fixture')).toBe('div'); 38
  • 40. Github Present for WebStorm users 40 https://github.com/thisisui/jetbrains-jasmine-test-startup
  • 41. 41 THANKS FOR YOUR TIME QUESTIONS?