如何测试已触发的事件及其值?

How to test for an event to have been fired and its value?

我找不到任何工作示例来测试事件是否已发出以及发出的值是否符合预期。

这是发出消息的 class 及其父级:

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;

这是我当前的测试代码:

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.
    });
});

我希望这很简单,但不知何故我遗漏了一些东西。

谢谢, 詹斯

您可以断言间谍已被调用一次并使用预期参数调用,如下所示

sinon.assert.calledOnce(fhParseSpy);
sinon.assert.calledWith(fhParseSpy, 'success');

你快到了。要检查该值,我们必须在 mocha 中调用 done() 以告知我们的测试已完成。

代码

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");      
  });
});

希望对您有所帮助