Justin Searls: JavaScript testing tactics

Orde Saunders' avatarPublished: by Orde Saunders

Justin Searls (@searls) was talking about JavaScript testing tactics at Scotland.js, these are my notes from his talk.

}); crying mustache.

Using coffee script can make for much more readable tests.

Test runners

Plain HTML test runners don't scale well.  Feedback often isn't fast enough, especially with front end JavaScript in server side tools.  Testem and Lineman are front end optimised.  Tests should run in under 300ms

Ajax and UI

Don't fake XHR or fake events - too integrated for unit tests.  Safe tests don't care about the code - like users.  Unit tests separate you from frameworks.  Inbetween is a grey area that causes problems.  If you mock something you don't own you create problems.  No pressure to improve private APIs.

Wrap native and 3rd party libs with objects I own then mock the wrappers away.  Test pain? -> improve wrapper API.  Wrapper specify dependence, can be changed in one file.  Don't test wrappers.

Asyncronous code

Don't write async tests of async code.  Lose execution control, lots of noise in setup, speed/timeout concerns, hard to debug race conditions => too many reasons for a test to fail.

Only write async APIs when they're useful to circumvent blocking.  Pull async in decorators and mixins.

The DOM

Don't avoid testing the DOM because it's hard.  Don't use HTML fixture files, especially when they're shared.  If you don't test DOM then your coverage is likely to be low.  If you wall off an area from testing then more code will end up there.

HTML fixtures tend to be large -> larger everything.  If you share a fixture between files you won't remove things in case they break other things.  Create HTML fixtures inline and arrive at single purpose DOM functions.

Less tactically

Know why you're testing.  Don't test just for the sake of having tests, they tend to lack clarity.

Push through the pain before knowing what is worth testing.

Easy to test code is easy to use.  Most JS is hard to test.

There's no Right Way(TM) in software, just thoughtful and thoughtless approaches.