Reputation:
I'm getting started writing unit tests for my javascript using Mocha with Chai, executing the tests via Node.
I would prefer it if I could run all of my tests via node and not require a real browser/html page.
The .js files are written as RequireJs modules, and I think I've got the hang of how to write some logical unit tests (i.e. ones which don't manipulate the DOM).
The bit I'm now stuck on is, how can I test functions which perform DOM manipulations?
Would I be forced to change the function signatures to pass in all elements I will manipulate as parameters? (Which probably isn't a bad thing to do - but could result in a lot of parameters being passed in if I'm working on many elements)?
Also, how can I test AJAX responses without having it hit the server?
What I'd like to do is simulate the AJAX response and test how my code handles it. e.g. fake a 404 response and see what happens.
I've heard of SinonJs, but not yet familiar with it.
If I'm using JQuery for my AJAX calls, should I be stubbing out $.ajax to get the desired result?
Based on the above, is there anything that I'll be missing on the js testing front? Is there anything obvious that I've described above that doesn't make sense or seems like I'm going about it the wrong way?
I've seen PhantomJs, but not quite sure where it fits in, it looks like it's best suited for testing against a running environment (I guess closer to integration testing) - is that a correct assumption?
Upvotes: 1
Views: 588
Reputation: 1707
Regarding testing of DOM manipulations, you can use a module called jsdom
which is a headless browser implemented in JavaScript. So you get a DOM but your tests still run in Node.js and are fast. The downside is that you cannot test for browser specific oddities because jsdom
is independent of other browsers.
Regarding testing of AJAX calls, sinon.js
is indeed very helpful. You can stub out $.ajax but if you want to test a level deeper, you can also stub out the XMLHttpRequest in your browser (or in jsdom, actually). I've written a blog post about this: http://nicolerauch.de/2015/12/20/lightweight-stubbing-of-ajax-requests-in-javascript.html (at the bottom there is a link to a Github repo with working code and tests using mocha and node.js and jsdom).
Upvotes: 0