Set of mock modules for easy testing (fs, http)
Set of mocks and utilities for easier unit testing with Node.js.
See http://howtonode.org/testing-private-state-and-mocking-deps for better explanation.
sudo npm install -g mocks # or install in local folder npm install mocks
// during unit test - we inject mock file system instead of real fsvar fs = require'fs';// even if this function is not public, we can test it directlyvarvar filtered =waiting = 0;collectionforEachwaiting++;fsstatfileif !err && statisFile filteredpushfile;waiting--;if !waiting donenull filtered;;;;
# simple unit test (jasmine syntax, coffescript)describe 'app'->mocks = require 'mocks'loadFile = mocksloadFileapp = done = nullbeforeEach ->done = jasminecreateSpy 'done'# load the file and inject fake fs moduleapp = loadFile __dirname + '/app.js'fs: mocksfscreate'bin':'run.sh': 1'install.sh': 1'home':'some.js': 1'another.txt': 1'one.js': 1'two.js': 1'three.js': 1it 'should return only existing files'->doneandCallFakeexpecterrtoBeFalsyexpectfilteredtoEqual '/bin/run.sh'appfilterOnlyExistingFiles '/bin/run.sh''/non.txt'donewaitsFor -> donecallCountit 'should ignore directories'->doneandCallFakeexpectfilteredtoEqual '/bin/run.sh''/home/some.js'appfilterOnlyExistingFiles '/bin/run.sh''/home''/home/some.js'donewaitsFor -> donecallCount
Non-blocking I/O operations can return in random order. Let's say you read a content of two files (asynchronously). There is no guarantee, that you get the content in right order. That's fine, but we want to test our code, whether it can handle such a situation and still work properly. In that case, you can use
predictableNextTick, which process callbacks depending on given pattern.
it 'should preserve order'->doneandCallFakeexpectfilteredtoEqual '/one.js''/two.js''/three.js'appfilterOnlyExistingFiles '/one.js''/two.js''/three.js'donewaitsFor -> donecallCount
This test will always pass. That's cool, as we like to see tests passing. The bad thing is, that it does not work in production, with real file system, as it might return in different order...
So, we need to test, whether our app works even when the
fs returns in random order. Having randomness in unit tests is not good habit, as it leads to flaky tests.
Let's change the previous unit test to this:
it 'should preserve order'->doneandCallFakeexpectfilteredtoEqual '/one.js''/two.js''/three.js'mocks.predictableNextTick.pattern = 201appfilterOnlyExistingFiles '/one.js''/two.js''/three.js'donewaitsFor -> donecallCount
Now, the unit test fails, because our fake file system calls back in different order. Note, it's not random, as you explicitly specified the pattern (2, 0, 1), so it the fake fs will consistently call back in this order: /three.js, /one.js, two.js.
I will keep adding more and of course if anyone wants to help - pull requests are more than welcomed.