Reputation: 839
I created a simple class for polling by Event Emitter
of Nodejs
For example:
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"
}
}
But I don't know to write the right test for Class
. This my unit test
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;
});
});
But It always false
1) Polling
should emit the function:
AssertionError: expected false to be true
+ expected - actual
-false
+true
Please tell me what's wrong with my test file. Thank you very much !
Upvotes: 0
Views: 581
Reputation: 16127
You can follow sinon doc
Quick fix
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;
});
});
Upvotes: 1