Event Emitter Nodejs的单元测试?

时间:2019-09-23 07:28:20

标签: node.js mocha sinon eventemitter

我创建了一个简单的类,用于Event Emitter的Node.js进行轮询 例如:

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

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

1 个答案:

答案 0 :(得分:1)

您可以关注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;
  });
});