node.js - 如何测试已触发的事件及其值?
问题描述
我找不到任何工作示例来测试是否发出事件以及发出的值是否符合预期。
这是发出消息的类及其父类:
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');
推荐阅读
- python - Python提取文件名正则表达式的一部分
- c++ - 更快的镜像算法
- javascript - javascript中日期格式错误的格式
- angular - 找不到名称'keyof'
- android - 在 AOSP 7.1 中链接预建共享库时未定义的引用
- sparql - 如何按城市过滤结果?
- ios - 在原生 iOS 应用程序中集成响应式 html 网页并使用 Apache Cordova 进行通信
- ios - 我想在不让他们安装应用程序的情况下向用户的电话号码发送图片和消息。我正在使用 firebase 进行存储(swift iOS)
- scala - 除了反射之外,有没有办法在 Scala 中创建泛型类型的实例
- c++ - 在抛出 'std::invalid_argument' what() 实例后调用终止:leetcode 问题中的 stoi 错误