Here are some examples of testing NodeJS with Sinon.
In these examples, I am using sinon@4.5.0 with node v6.14.3
- Use a sandbox because it restores all stubs, spies, timers, etc.
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.restore();
});
- Stubbing class methods.
it("Testing method helloWorld()", () => {
const stubby = sandbox.create(ShinyObject.prototype, "helloWorld");
const obj = new ShinyObject();
obj.helloWorld();
expect(stubby.called).true;
});
- Stub timers, nextInterval(), nextTimeout()
it("Testing timers", () => {
sandbox.useFakeTimers();
let value = 0;
setTimeout(() => {
value = 1;
}, 500);
sandbox.clock.tick(500);
expect(value).eq(1);
});