Rebecca Murphey: Writing testable JavaScript

Orde Saunders' avatarPublished: by Orde Saunders

Rebecca Murphey (@rmurphey) was speaking at Full Frontal about how to write testable JavaScript code, these are my notes from her talk.

How do we write code that is testable? We know our code is hard to test.

Facts of life:

  • You will design your code
  • You will test your code
  • You will refactor your code
  • Other people will use your code
  • There will be bugs

A typical example of code might be a 30 line form submit handler. Typically we test that we get the result we want - this is integration testing, checks that all the parts work together. Selinum in the browser is an example of this.

A better approach is unit testing which tests a unit of functionality. You have to write code that can be tested. When you refactor you can check you haven't broken anything. Other people can use them to understand what you code is expected to do.

Difficult to test:

  • annonymous functions
  • complex functions
  • lack of configurability
  • hidden or shared state
  • tightly coupled

Choose your own adventure code.

How do we write testable code?

Disentangle your code.

  • presentation & interaction
  • data/ server communication
  • application state
  • setup

Guiding principles:

  • use constructors that create instances
  • support configurability
  • keep methods simple
  • don't intermingle responsibilities

Test first - write tests first then write code that passes the tests.

Instead of writing complex functions that are bound to events with callbacks build individual functions that have defined calls and results.

Don't test the server, use mocks for server calls.


  • grunt + quit + phantomjs
  • grunt + grunt-mocha + phantomjs
  • grunt + grunt-jasmine + phantomjs
  • sinon.js (mocks server)
  • chai.js / expect.js (assertion libraries for mocha)

Comments, suggestions, corrections? Contact me via this website