Skip to content

Instantly share code, notes, and snippets.

@datvong-wm
Last active August 19, 2018 05:12
Show Gist options
  • Save datvong-wm/e4f60e8f9352c61dde0f969fe48b5ba1 to your computer and use it in GitHub Desktop.
Save datvong-wm/e4f60e8f9352c61dde0f969fe48b5ba1 to your computer and use it in GitHub Desktop.
Sinon patterns and How-To

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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment