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
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
A presentation made for the AngularJS-IL meetup group that took place in May 2014 at Google TLV Campus. its a demonstration of Unit testing an AngularJS component with jasmine and karma.
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.
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.
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
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
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.
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.
A presentation made for the AngularJS-IL meetup group that took place in May 2014 at Google TLV Campus. its a demonstration of Unit testing an AngularJS component with jasmine and karma.
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.
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.
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
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
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.
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.
The Dark Side of Single Page ApplicationsDor Kalev
The story of all the pitfalls we had while transferring FTBpro.com from the good old web to a Backbone single page application... and all the great solutions we've came up with
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)
So, you've made the ferpect Single Page Application. It has all the bells and whistles, and uses all the flashing new frameworks.
But how do you know it works, and how do you know that it will continue to work in this world of continuous delivery? This session will try to explain how to do end-to-edn testing of the system, how to test the application server code, and how to test the code the executes on the client.
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/
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
This talk takes a deep dive into asynchronous programming patterns and practices, with an emphasis on the promise pattern.
We go through the basics of the event loop, highlighting the drawbacks of asynchronous programming in a naive callback style. Fortunately, we can use the magic of promises to escape from callback hell with a powerful and unified interface for async APIs. Finally, we take a quick look at the possibilities for using coroutines both in current and future (ECMAScript Harmony) JavaScript.
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
There are more smart people building software now than there have been at any point in the past, which means that it's more important than ever to stay on top of new developments, libraries, frameworks, and everything else. To really take advantage of this wealth of innovation, however, you've got to look beyond your normal community -- what's going on in Python? And how can we use that to make our Ruby lives easier? In this session, we'll explore that question. We'll look at actual examples of code and concepts borrowed and reimplemented to form a better idea of when it's appropriate and when it'll fall flat.
The next version of JavaScript, ES6, is starting to arrive. Many of its features are simple enhancements to the language we already have: things like arrow functions, class syntax, and destructuring. But other features will change the way we program JavaScript, fundamentally expanding the capabilities of the language and reshaping our future codebases. In this talk we'll focus on two of these, discovering the the myriad possibilities of generators and the many tricks you can pull of with template strings.
Node.js has given JavaScript a new resurgence as a server-side language. No longer just for image rollovers and AJAX, JS is now available as a platform for creating lightning-fast, lightweight, networked applications. In this session, we will move beyond Node’s base web servers and Twitter applications, and into module development: those small, reusable components that are the foundation for every business application on every platform. Learn how to create a module within Node.js, how to test your module and validate functionality, and how to get your creation distributed into the wild. With this knowledge, you can make the next great Node package and become famous.
JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
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.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
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.
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.
3. https://github.com/pivotal/jasmine/wiki
A BDD Framework for testing JavaScript.
- Does not depend on any other JavaScript frameworks.
- Does not require a DOM.
- It has a clean, obvious syntax
- Heavily influenced by, and borrows the best parts of, ScrewUnit,
JSSpec, JSpec, and of course RSpec.
14. https://github.com/pivotal/jasmine/wiki
Matchers
"How you can evaluate your code behavior"
expect(x).toEqual(y);
expect(x).toBe(y);
expect(x).toMatch(pattern);
expect(x).toBeDefined();
expect(x).toBeNull();
expect(x).toBeTruthy();
expect(x).toBeFalsy();
expect(x).toContain(y);
expect(x).toBeLessThan(y);
expect(x).toBeGreaterThan(y);
expect(fn).toThrow(e);
expect(x).not.toEqual(y);
Every matcher's criteria can be inverted by prepending .not
15. https://github.com/pivotal/jasmine/wiki
Your own matcher
"We are not slave, we wanna make our own matchers"
describe('Hello world', function() {
beforeEach(function() { this.addMatchers({ toBeDivisibleByTwo: function() {
return (this.actual % 2) === 0;
}
});
});
it('is divisible by 2', function() {
expect(gimmeANumber()).toBeDivisibleByTwo();
});
});
17. https://github.com/pivotal/jasmine/wiki
SPIES
"Jasmine Spies are test doubles that can act as stubs,
spies, fakes or when used in an expecation, mocks."
Spies should be created in test setup, before expectations.
Spies are torn down at the end of every spec.
Spies can be checked if they were called or not and what the calling
params were.
A Spy has the following fields:
wasCalled, callCount, mostRecentCall, and argsForCall
18. https://github.com/pivotal/jasmine/wiki
SPIES II
spying on an existing function that you don't touch, with spyOn()
var Person = function() { };
Person.prototype.helloSomeone = function(toGreet) { return this.sayHello() + " " + toGreet; };
Person.prototype.sayHello = function() { return "Hello"; };
we want to make sure it calls the sayHello() function when we call the helloSomeone() function
describe("Person", function() {
it("calls the sayHello() function", function() { var fakePerson = new Person(); spyOn(fakePerson, "sayHello");
fakePerson.helloSomeone("world"); expect(fakePerson.sayHello).toHaveBeenCalled();
}); });
19. https://github.com/pivotal/jasmine/wiki
SPIES III
spying on an existing function that you don't touch, with spyOn()
var Person = function() { };
Person.prototype.helloSomeone = function(toGreet) { return this.sayHello() + " " + toGreet; };
Person.prototype.sayHello = function() { return "Hello"; };
Now we want to make sure that helloSomeone is called with "world" as its argument
describe("Person", function() {
it("greets the world", function() {
var fakePerson = new Person();
spyOn(fakePerson, "helloSomeone");
fakePerson.helloSomeone("world");
expect(fakePerson.helloSomeone).toHaveBeenCalledWith("world");
}); });
20. https://github.com/pivotal/jasmine/wiki
SPIES IV
Spying on an existing function that you modify: use of jasmine.createSpy()
var Person = function() { };
Person.prototype.helloSomeone = function(toGreet) { return this.sayHello() + " " + toGreet; };
Person.prototype.sayHello = function() { return "Hello"; };
With Jasmine, you can "empty" the contents of the function while you're testing
describe("Person", function() {
it("says hello", function() {
var fakePerson = new Person();
fakePerson.sayHello = jasmine.createSpy("Say-hello spy");
fakePerson.helloSomeone("world");
expect(fakePerson.sayHello).toHaveBeenCalled();
});
});
21. https://github.com/pivotal/jasmine/wiki
SPIES V
Spying on an existing function that you modify: use of jasmine.createSpy()
var Person = function() { };
Person.prototype.helloSomeone = function(toGreet) { return this.sayHello() + " " + toGreet; };
Person.prototype.sayHello = function() { return "Hello"; };
You can specify that a spy function return something
fakePerson.sayHello = jasmine.createSpy('"Say hello" spy').andReturn("ello ello");
You can even give your spy functions something to do
fakePerson.sayHello = jasmine.createSpy('"Say hello" spy').andCallFake(function() { document.write("Time to say hello!");
return "bonjour"; });
23. https://github.com/pivotal/jasmine/wiki
Spy-Specific Matchers
When working with spies, these matchers are quite handy:
expect(x).toHaveBeenCalled()
expect(x).toHaveBeenCalledWith(arguments)
expect(x).not.toHaveBeenCalled()
expect(x).not.toHaveBeenCalledWith(arguments)
Spies can be trained to respond in a variety of ways when invoked:
spyOn(x, 'method').andCallThrough()
spyOn(x, 'method').andReturn(arguments)
spyOn(x, 'method').andThrow(exception)
spyOn(x, 'method').andCallFake(function)
24. https://github.com/pivotal/jasmine/wiki
Asynchronous specs
There are three Jasmine functions that hep you with asynchronicity: run(),
waitsFor(), and wait().
runs
run() blocks execute procedurally, so you don't have to worry about
asynchronous code screwing everything up.
28. https://github.com/pivotal/jasmine/wiki
Asynchronous specs V
waitsFor(function, optional message, optional timeout)
waitsFor() . Provides a better interface for pausing your spec until some other
work has completed.
Jasmine will wait until the provided function returns true before continuing
with the next block. This may mean waiting an arbitrary period of time, or you
may specify a maxiumum period in milliseconds before timing out.
describe("Calculator", function() {
it("should factor two huge numbers asynchronously", function() { var calc = new Calculator(); var answer = calc.
factor(18973547201226, 28460320801839); waitsFor(function() { return calc.answerHasBeenCalculated();
}, "It took too long to find those factors.", 10000);
runs(function() {
expect(answer).toEqual(9486773600613);
});
});
});
29. References
Jasmine Wiki
How do I Jasmine: Tutorial
Jasmine Railcast
30. You could look at these
Jasmine-JQuery: jQuery matchers and fixture loader for Jasmine
framework
Jasmine Species: Extended BDD grammar and reporting for
Jasmine
jasmine-headless-webkit: Uses the QtWebKit widget to run your
specs without needing to render a pixel.
JasmineRice: Utilizing (jasmine) and taking full advantage of the
Rails 3.1 asset pipeline jasmine rice removes any excuse YOU have for
not testing your out of control sprawl of coffeescript files.
31. You could look at these
Try Jasmine Online: start with jasmine from your browser :)