Unit testing Javascript applications with qunit and sinon

Training goals

  • Introduction to the tools (QUnit, Sinon)
  • Overview of the test runner (Karma)
  • How we integrate testing into a build

Qunit

TDD style testing framework that groups tests into modules and uses assertions to pass/fail tests.

 

http://qunitjs.com/

 

QUnit running in the browser.

Assertion Types

Truthiness  
assert.ok(value)
Boolean(value) === true
assert.notOk(value)
Boolean(value) === false
Equality  
assert.equal(value1, value2)
value1 == value2
assert.strictEqual(value1, value2)
value1 === value2
assert.notEqual(value1, value2)
value1 != value2
assert.notStrictEqual(value1, value2)
value1 !== value2
assert.deepEqual(value1, value2)
angular.equals(value1, value2)*

Assertion Types (continued)

Equality  
assert.notDeepEqual(value1, value2)
!angular.equals(value1, value2)*
Exceptions  
assert.throws(func, Error)
function func() { throw new Error; }

sinon.js

Test spies, stubs, and additional assertions for dependencies used within your test.

 

http://sinonjs.org/

 

sinon spies

  • When you want to inspect the inputs and return values of a function.
  • Validating your call stack
  • Keep them within the object / class under test

sinon stubs

  • When you want to inspect the inputs and return values of a function with predetermined behaviors.
  • Use for calls out to dependencies
    • Resources
    • Services
    • Really anything that is not the object / class under test.

sinon matchers

  • Indicate a level of specificity for matching values
  • Fuzzy or strict matching
  • Good for matching objects
  • Good for matching types like Array, RegExp, and Object
  • Good for testing truthy / falsy values

Karma

A pluggable, framework-agnostic test runner with support for multiple browsers and devices.

Karma monitoring multiple browsers.

final thoughts

  • Writing good tests is like writing good code - it takes practice and patterns
  • 100% coverage is NOT the goal
  • Stability is the goal
  • Tests help to define your interface

Questions?

Made with Slides.com