Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 事件发射器节点的单元测试?_Node.js_Mocha.js_Sinon_Eventemitter - Fatal编程技术网

Node.js 事件发射器节点的单元测试?

Node.js 事件发射器节点的单元测试?,node.js,mocha.js,sinon,eventemitter,Node.js,Mocha.js,Sinon,Eventemitter,我创建了一个简单的类,用于通过Nodejs的事件发射器进行轮询 例如: 从“事件”导入EventEmitter; 从“./config”导入配置; 导出类轮询器扩展了EventEmitter{ 构造函数(私有超时:number=config.pollingTime){ 超级(); this.timeout=超时; } 投票(){ setTimeout(()=>this.emit(“poll”),this.timeout); } onPoll(fn:任何){ this.on(“poll”,fn);

我创建了一个简单的类,用于通过Nodejs的
事件发射器进行轮询
例如:

从“事件”导入EventEmitter;
从“./config”导入配置;
导出类轮询器扩展了EventEmitter{
构造函数(私有超时:number=config.pollingTime){
超级();
this.timeout=超时;
}
投票(){
setTimeout(()=>this.emit(“poll”),this.timeout);
}
onPoll(fn:任何){
this.on(“poll”,fn);//侦听操作“poll”,并运行函数“fn”
}
}
但是我不知道如何为
类编写正确的测试。这是我的单元测试

从“Sinon”导入Sinon;
从“/polling”导入{Poller};
从“chai”导入{expect};
描述(“轮询”,()=>{
它(“应该发出函数”,async()=>{
设spy=Sinon.spy();
让轮询器=新轮询器();
民意测验者。onPoll(间谍);
poller.poll();
期待(间谍被叫)是真的;
});
});
但它总是假的

  1) Polling
       should emit the function:

      AssertionError: expected false to be true
      + expected - actual

      -false
      +true
请告诉我我的测试文件有什么问题。多谢各位

你可以跟着

快速修复

import Sinon from "sinon";
import { Poller } from "./polling";
import { expect } from "chai";
import config from "../config";

describe("Polling", () => {
  it("should emit the function", async () => {
    // create a clock to control setTimeout function
    const clock = Sinon.useFakeTimers();
    let spy = Sinon.spy();
    let poller = new Poller();

    poller.onPoll(spy);
    poller.poll(); // the setTimeout function has been locked

    // "unlock" the setTimeout function with a "tick"
    clock.tick(config.pollingTime + 10); // add 10ms to pass setTimeout in "poll()"

    expect(spy.called).to.be.true;
  });
});

使用本答案中描述的
sinon.useFakeTimers()
,谢谢您的回复。它起作用了。你能把你的答案贴出来吗?这样我就可以替你接受了!