Skip to content

Instantly share code, notes, and snippets.

@rehia
Last active August 29, 2015 14:11
Show Gist options
  • Save rehia/b47372cc8496cfffa9a0 to your computer and use it in GitHub Desktop.
Save rehia/b47372cc8496cfffa9a0 to your computer and use it in GitHub Desktop.
How to test that something didn't happen in JavaScript other than with setTimeout ?
function Foo (emitter, expectedPerson) {
this.waitForSomething = function(callback) {
emitter.on('something_happened', function(person) {
if (expectedPerson === person) {
callback(person);
}
});
};
return this;
};
module.exports = Foo;
var EventEmitter = require('events').EventEmitter;
var Foo = require('./foo');
describe('Let’s test that something didn’t happen', function () {
var emitter, bar, foo;
beforeEach(function(){
emitter = new EventEmitter();
bar = 'John';
foo = new Foo(bar, emitter);
});
it('should catch a corresponding event', function (done) {
var callback = function(name) {
name.should.equal(bar);
done();
}; // if callback is not called, there's a timeout (at least with Mocha)
foo.waitForSomething(callback);
process.nextTick(function() {
emitter.emit('something_happened', bar);
});
});
it('should not catch a mismatched event', function (done) {
var timeout
var callback = function(name) {
clearTimeout(timeout);
done(new Error('event should not have been caught'));
};
timeout = setTimeout(done, 50); // if callback has not been called, it's fine, test is green.
foo.waitForSomething(callback);
process.nextTick(function() {
emitter.emit('something_happened', 'Bill'); // John is expected. Not Bill
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment