I couldn't find any working examples to test for whether an event was emitted and whether the emitted value is as expected.
Here is the class that emits messages and its parent:
const EventEmitter = require('events').EventEmitter;
class FileHandler extends EventEmitter {
constructor() {
super();
}
canHandle(filePath) {
emit('not super type');
}
parseFile(filePath) {
emit('supper parsing failed');
}
whoAmI() {
return this.emit('who',"FileHandler");
}
}
module.exports = FileHandler;
//diff file
const FileHandler = require('./FileHandler');
class FileHandlerEstedamah extends FileHandler {
constructor() {
super();
}
canHandle(filePath) {
this.emit('FH_check','fail, not my type');
}
parseFile(filePath) {
this.emit('FH_parse','success');
}
}
module.exports = FileHandlerEstedamah;
Here is my current test code:
var sinon = require('sinon');
var chai = require('chai');
const FileHandlerEstedamah = require("../FileHandlerEstedamah");
describe('FH_parse', function() {
it('should fire an FH_parse event', function(){
const fhe = new FileHandlerEstedamah();
var fhParseSpy = sinon.spy();
fhe.on('FH_parse',fhParseSpy);
fhe.parseFile("path");
//I tried a large number of variants of expect, assert, etc to no avail.
});
});
I expected this to be straightforward but somehow I am missing something.
Thank you, Jens
You almost nearly there. To check the value, we must call done()
after that in mocha to tell that our test is finish.
The code
const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');
const FileHandlerEstedamah = require("../FileHandlerEstedamah");
describe('FH_parse', function() {
it('should fire an FH_parse event', function(done){ // specify done here
const fhe = new FileHandlerEstedamah();
fhe.on('FH_parse', (data) => {
assert.equal(data, 'success'); // check the value expectation here
done(); // hey mocha, I'm finished with this test
});
fhe.parseFile("path");
});
});
Hope it helps