Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  120] [ 2]  / answers: 1 / hits: 28822  / 10 Years ago, sun, november 30, 2014, 12:00:00

Lets say I want to write this simple task. But I want to write a test validating that:




  1. This task emits object.

  2. Object has a property name.



I'm testing with mocha and chai expect.



Thanks in advance. I've tried every possible variant that came to mind, but could not come up with a solution.



var util = require('util'),
EventEmitter = require('events').EventEmitter;

function SomeTask() {
var self = this;

setInterval(function() {
self.emit('data', { name: 'name' });
}, 5000);
}

util.inherits(SomeTask, EventEmitter);

module.exports = SomeTask;

More From » node.js

 Answers
34

Here's an example using spies. https://github.com/mochajs/mocha/wiki/Spies



var sinon = require('sinon');
var EventEmitter = require('events').EventEmitter;

describe('EventEmitter', function(){
describe('#emit()', function(){
it('should invoke the callback', function(){
var spy = sinon.spy();
var emitter = new EventEmitter;

emitter.on('foo', spy);
emitter.emit('foo');
spy.called.should.equal.true;
})

it('should pass arguments to the callbacks', function(){
var spy = sinon.spy();
var emitter = new EventEmitter;

emitter.on('foo', spy);
emitter.emit('foo', 'bar', 'baz');
sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, 'bar', 'baz');
})
})
})

[#68653] Thursday, November 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devlin

Total Points: 474
Total Questions: 113
Total Answers: 100

Location: Sweden
Member since Fri, Apr 16, 2021
3 Years ago
devlin questions
Tue, Apr 27, 21, 00:00, 3 Years ago
Sat, Oct 31, 20, 00:00, 4 Years ago
Fri, Aug 28, 20, 00:00, 4 Years ago
;