事件发射器 Nodejs 的单元测试?

Unit test for Event Emitter Nodejs?

我创建了一个简单的 class 用于 Nodejs Event Emitter 的轮询 例如:

import EventEmitter from "events";
import config from "../config";

export class Poller extends EventEmitter {
  constructor(private timeout: number = config.pollingTime) {
    super();
    this.timeout = timeout;
  }

  poll() {
    setTimeout(() => this.emit("poll"), this.timeout);
  }

  onPoll(fn: any) {
    this.on("poll", fn); // listen action "poll", and run function "fn"
  }
}

但我不知道为 Class 编写正确的测试。这是我的单元测试

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

describe("Polling", () => {
  it("should emit the function", async () => {
    let spy = Sinon.spy();
    let poller = new Poller();

    poller.onPoll(spy);
    poller.poll();

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

但它总是错误的

  1) Polling
       should emit the function:

      AssertionError: expected false to be true
      + expected - actual

      -false
      +true

请告诉我我的测试文件有什么问题。非常感谢!

你可以关注sinon doc

快速修复

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