首页 > 解决方案 > 如何测试已触发的事件及其值?

问题描述

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

这是发出消息的类及其父类:

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

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

谢谢你,延斯

标签: node.jsmocha.jssinonchaieventemitter

解决方案


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

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

推荐阅读