Unit testing JavaScript code with Jasmine allows developers to test functionality in isolation through matchers, spies, and asynchronous handling. Key benefits include cheaper QA, better documentation, improved code quality, and easier debugging. While some are deterred by complex asynchronous code or small projects, unit testing pays off through early bug detection and confidence that features work as intended.
This presentation is prepared for SVCC 2014 on Javascript Testing with Jasmine. It basically goes through basic Jasmine feature and provide tips for developers when they decide to start testing.
Slides from my Lonestar Ruby Conf 2011 presentation.
*** Video of presentation: http://confreaks.com/videos/2531-lsrc2011-testing-javascript-with-jasmine ***
Agenda:
- Briefly cover why you should unit test
- Discuss what Jasmine is and isn't
- Show syntax with comparisons to RSpec
- Jasmine with:
- Vanilla JavaScript
- Jasmine with jQuery
- Jasmine with Ruby (not Rails)
- Jasmine with Rails
- Evergreen
- capybara-webkit
- Where does CoffeeScript, node.js, etc. fit in?
- Other helpful libraries/Wrap-up
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
Code: https://github.com/larsthorup/jasmine-demo-advanced
Video: https://www.youtube.com/watch?v=g4eQplHxU18
Audio: https://www.youtube.com/watch?v=8FUwc3gZDMw
Unit testing front-end JavaScript presents its own unique set of challenges. In this session we will look at number of different techniques to tackle these challenges and make our JavaScript unit tests fast and robust. We plan to cover the following subjects:
* Mocking and spy techniques to avoid dependencies on
- Functions, methods and constructor functions
- Time (new Date())
- Timers (setTimeout, setInterval)
- Ajax requests
- The DOM
- Events
* Expressive matchers
- Jasmine-jQuery
* Structuring tests for reuse and readability
* Testing browser-specific behaviour
This presentation is prepared for SVCC 2014 on Javascript Testing with Jasmine. It basically goes through basic Jasmine feature and provide tips for developers when they decide to start testing.
Slides from my Lonestar Ruby Conf 2011 presentation.
*** Video of presentation: http://confreaks.com/videos/2531-lsrc2011-testing-javascript-with-jasmine ***
Agenda:
- Briefly cover why you should unit test
- Discuss what Jasmine is and isn't
- Show syntax with comparisons to RSpec
- Jasmine with:
- Vanilla JavaScript
- Jasmine with jQuery
- Jasmine with Ruby (not Rails)
- Jasmine with Rails
- Evergreen
- capybara-webkit
- Where does CoffeeScript, node.js, etc. fit in?
- Other helpful libraries/Wrap-up
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
If you listen to backend developers, they will tell you that writing unit tests is essential to good karma. Pay it forward with tests and get back a reliable application. But getting unit tests running on the front end in a “real” application can be a lot more challenging. This intermediate-beginner level workshop will cover how to get setup for writing unit tests, and how to write front-end and end-to-end oriented unit tests for a variety of use cases all for AngularJS. We will work from a series of use cases, transform those into formal acceptance tests, write failing unit tests and then resolve those tests writing code with Angular, html/jade/css and node.
Presentation by Laura Ferguson and Boris Kan @ Create, inc, 2015
Advanced Jasmine - Front-End JavaScript Unit TestingLars Thorup
Code: https://github.com/larsthorup/jasmine-demo-advanced
Video: https://www.youtube.com/watch?v=g4eQplHxU18
Audio: https://www.youtube.com/watch?v=8FUwc3gZDMw
Unit testing front-end JavaScript presents its own unique set of challenges. In this session we will look at number of different techniques to tackle these challenges and make our JavaScript unit tests fast and robust. We plan to cover the following subjects:
* Mocking and spy techniques to avoid dependencies on
- Functions, methods and constructor functions
- Time (new Date())
- Timers (setTimeout, setInterval)
- Ajax requests
- The DOM
- Events
* Expressive matchers
- Jasmine-jQuery
* Structuring tests for reuse and readability
* Testing browser-specific behaviour
Even for JavaScript software developers well-versed in Agile practices, using test-driven development in Node.js and Express can be challenging. In this presentation, I identify solutions to some of the most significant challenges to using TDD with Express, including mocking data in MongoDB / Mongoose, using promises to control asynchronous testing in Mocha with Chai, and separating concerns to write robust and enduring test suites.
This presentation deals with a complex approach to application testing in back end and front end parts, tests writing and common mistakes. It also includes a short overview of libraries and frameworks for creation of tests, as well as practical examples of code.
Presentation by Pavlo Iuriichuk, Lead Software Engineer, GlobalLogic, Kyiv), delivered at an open techtalk on December 11, 2014.
More details - http://globallogic.com.ua/report-web-testing-techtalk-2014
Slides from a talk about unit tests in Node.js. The talk was held as a part of an internal Node.js course in ironSource's offices in Tel-Aviv. On Wednesday, September 14th, 2016
Unit Testing Express and Koa Middleware in ES2015Morris Singer
Even for JavaScript software developers well-versed in Agile practices, using test-driven development in the development of Node.js-based webservers can be challenging. In this presentation, I identify solutions to some of the most significant challenges to using TDD to build middleware stacks, with a focus on Express and Koa.
Test-Driven Development of AngularJS ApplicationsFITC
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
OVERVIEW
AngularJS is an open-source JavaScript framework, maintained by Google, that simplifies development of single-page applications. This session will provide an overview of AngularJS framework and demonstrate test-driven development of single-page applications.
In this session Andy will present a walkthrough of Angular’s core features such as dependency injector and directives. He will showcase a test-driven development of AngularJS applications using Jasmine and explain Angular’s data bindings that allow for creation of views and controllers that update automatically in response to data changes. He will also demo Angular’s deep linking and front-end validations and present integration with Ruby On Rails back end using AngularJS AJAX abstractions. Finally, Andy will utilize AngularJS directives and components to create reusable UI elements.
In summary, AngularJS is a great framework for creating complex single-page applications. Attendees will leave the talk with a solid understanding of Angular’s test-driven development process.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
Jasmine - A BDD test framework for JavaScriptSumanth krishna
Jasmine is the BDD implementation for JavaScript. With it's Behavior Driven approach developers are empowered with more testing capabiliites.
Although BDD is principally an idea about how software development should be managed by both business interests and technical insight, the practice of BDD does assume the use of specialized software tools to support the development process.
Even for JavaScript software developers well-versed in Agile practices, using test-driven development in Node.js and Express can be challenging. In this presentation, I identify solutions to some of the most significant challenges to using TDD with Express, including mocking data in MongoDB / Mongoose, using promises to control asynchronous testing in Mocha with Chai, and separating concerns to write robust and enduring test suites.
This presentation deals with a complex approach to application testing in back end and front end parts, tests writing and common mistakes. It also includes a short overview of libraries and frameworks for creation of tests, as well as practical examples of code.
Presentation by Pavlo Iuriichuk, Lead Software Engineer, GlobalLogic, Kyiv), delivered at an open techtalk on December 11, 2014.
More details - http://globallogic.com.ua/report-web-testing-techtalk-2014
Slides from a talk about unit tests in Node.js. The talk was held as a part of an internal Node.js course in ironSource's offices in Tel-Aviv. On Wednesday, September 14th, 2016
Unit Testing Express and Koa Middleware in ES2015Morris Singer
Even for JavaScript software developers well-versed in Agile practices, using test-driven development in the development of Node.js-based webservers can be challenging. In this presentation, I identify solutions to some of the most significant challenges to using TDD to build middleware stacks, with a focus on Express and Koa.
Test-Driven Development of AngularJS ApplicationsFITC
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
OVERVIEW
AngularJS is an open-source JavaScript framework, maintained by Google, that simplifies development of single-page applications. This session will provide an overview of AngularJS framework and demonstrate test-driven development of single-page applications.
In this session Andy will present a walkthrough of Angular’s core features such as dependency injector and directives. He will showcase a test-driven development of AngularJS applications using Jasmine and explain Angular’s data bindings that allow for creation of views and controllers that update automatically in response to data changes. He will also demo Angular’s deep linking and front-end validations and present integration with Ruby On Rails back end using AngularJS AJAX abstractions. Finally, Andy will utilize AngularJS directives and components to create reusable UI elements.
In summary, AngularJS is a great framework for creating complex single-page applications. Attendees will leave the talk with a solid understanding of Angular’s test-driven development process.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
Jasmine - A BDD test framework for JavaScriptSumanth krishna
Jasmine is the BDD implementation for JavaScript. With it's Behavior Driven approach developers are empowered with more testing capabiliites.
Although BDD is principally an idea about how software development should be managed by both business interests and technical insight, the practice of BDD does assume the use of specialized software tools to support the development process.
DEV.BG - Angular 1 and Jasmine (Unit Testing and TDD)Dimitar Danailov
I'd like to share: shares common pitfalls in writing unreadable, unmaintainable unit tests in javascript.
Agenda:
1. My experience with Enterprise projects - good, bad and ugly part
2. What is TDD
3. What is Unit Testing
4. Understanding Mock and Stub Objects
5. TDD - Possible Mistakes
6. Angular and Unit Testing and yohottowel (jpapa.me/yohottowel)
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...Jasmine Sandler
Jasmine Sandler, Globally industry awarded Digital Marketing Strategist, Keynote Speaker and Social Media Trainer shares her consulting client case studies.
Annotated slides from my "Behavior Driven Development" course. Released under Creative Commons share-alike, commercial and derivatives allowed: http://creativecommons.org/licenses/by-sa/3.0/
2013-06-15 - Software Craftsmanship mit JavaScriptJohannes Hoppe
Entwickeln Sie Clean Code mit JavaScript. Den “Software Craftsman” zeichnen dabei Wissen, Werkzeuge und Wiederholung aus. Diese drei Grundfeste werden speziell für JavaScript beleuchtet. Lernen Sie die wichtigsten Patterns für eine stabile und wartbare Website kennen. Überprüfen Sie Ihre persönliche Werkzeugkiste für Entwicklung, Testing und Deployment. Schließen Sie Bekanntschaft mit Code Katas für JavaScript.
2013-06-24 - Software Craftsmanship with JavaScriptJohannes Hoppe
Entwickeln Sie Clean Code mit JavaScript. Den “Software Craftsman” zeichnen dabei Wissen, Werkzeuge und Wiederholung aus. Diese drei Grundfeste werden speziell für JavaScript beleuchtet. Lernen Sie die wichtigsten Patterns für eine stabile und wartbare Website kennen. Überprüfen Sie Ihre persönliche Werkzeugkiste für Entwicklung, Testing und Deployment. Schließen Sie Bekanntschaft mit Code Katas für JavaScript.
Testing most things in JavaScript - LeedsJS 31/05/2017Colin Oakley
Testing is important - it can improve the quality of your code and give you the reassurance to refactor without fear of destroying your application.
My talk will cover different types of automated testing in javascript (unit, integration, acceptance) and some regression as well tools to help standardise code (like js lint).
I'll also talk about automated build tools like jenkins and travis ci.
If you don’t test it, how do you know it works? Over the past few years, we have been compelled to write unit and integration tests for our applications--code that validates code--and it is these tests that change a one-off tool into a well-architected, robust, business-ready application. Yet, every new framework requires a new testing framework, so in this session, we will discuss testing frameworks for node.js. You will walk away with a solid understanding of how to write tests against your node.js applications and modules, leading to confidence that your work is business-ready.
FrontDays #3. Иван Федяев, Эволюция JavaScript. Обзор нововведений ECMAScript 6FrontDays
Общий обзор новых возможностей ES6, сравнение с более ранними стандартами. Почему стоит использовать ES6 уже сейчас? Поговорим о таких нововведениях как: поддержка классов, шаблоны строк, модули, стрелочные функции, генераторы и о многом другом.
Similar to Jasmine - why JS tests don't smell fishy (20)
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
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
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
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
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
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
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)