Модульный тест для Event Emitter Nodejs? - PullRequest
0 голосов
/ 23 сентября 2019

Я создал простой класс для опроса Event Emitter из Nodejs Например:

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 Ответ

1 голос
/ 23 сентября 2019

Вы можете следовать 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;
  });
});
...