Book Image

Test-Driven JavaScript Development

By : Ravi Kumar Gupta
Book Image

Test-Driven JavaScript Development

By: Ravi Kumar Gupta

Overview of this book

Initially, all processing used to happen on the server-side and simple output was the response to web browsers. Nowadays, there are so many JavaScript frameworks and libraries created that help readers to create charts, animations, simulations, and so on. By the time a project finishes or reaches a stable state, so much JavaScript code has already been written that changing and maintaining it further is tedious. Here comes the importance of automated testing and more specifically, developing all that code in a test-driven environment. Test-driven development is a methodology that makes testing the central part of the design process – before writing code developers decide upon the conditions that code must meet to pass a test. The end goal is to help the readers understand the importance and process of using TDD as a part of development. This book starts with the details about test-driven development, its importance, need, and benefits. Later the book introduces popular tools and frameworks like YUI, Karma, QUnit, DalekJS, JsUnit and goes on to utilize Jasmine, Mocha, Karma for advanced concepts like feature detection, server-side testing, and patterns. We are going to understand, write, and run tests, and further debug our programs. The book concludes with best practices in JavaScript testing. By the end of the book, the readers will know why they should test, how to do it most efficiently, and will have a number of versatile tests (and methods for devising new tests) to get to work immediately.
Table of Contents (16 chapters)
Test-Driven JavaScript Development
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Spies


A spy is an emulation of a function or object, irrespective of which function/object is defined or not. There are times when we need stubs for the functions we need to use for performing testing. Jasmine has spies for this purpose. A spy can stub functions but can only exist within describe and it block if it is defined.

Apart from the matchers we read in this chapter, there are special matchers just for spies. One is toHaveBeenCalled(), which returns true if the spy was called. Another one is toHaveBeenCalledWith(), which returns true if the spy was called with arguments.

Let's see the following example to understand how spies work. The following is our source for an Employee function in the employee.js file created in the src folder:

var DEFAULT_SALARY = 1000;

function Employee(name, grade, department, salary) {
    this.name = name;
    this.grade  = grade;
    this.department = department;

    this.salary = salary || 0;
}

Employee.prototype.getName = function() {
    return this...