-
-
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 ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Foo (emitter, expectedPerson) { | |
this.waitForSomething = function(callback) { | |
emitter.on('something_happened', function(person) { | |
if (expectedPerson === person) { | |
callback(person); | |
} | |
}); | |
}; | |
return this; | |
}; | |
module.exports = Foo; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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