← Back
chai sinon testing

Stubs with Chai and Sinon

Since I started to use jest this has been my library of choice to test in Javascript. And I didn't look back.

But today I had to write some tests with Chai (assertion library) and Sinon for stubs. In adition, the project also uses should syntax instead of expect (that I'm more used to). And moreover, the sinon-chai library is not installed.

Example 1: stub request-promise #

Ok, I want to unit test a service that make a POST request to an external API with the (almost deprecated) request-promise:

const chai = require("chai");
chai.should();
const sinon = require("sinon");
const rp = require("request-promise");
const myService = require("../../../app/services/myService");

describe("MyService", () => {
it("sends requests to Workato http endpoint", async () => {
const spy = sinon.stub(rp, "post");
spy.returns(Promise.resolve({ id: "the-id" }));

const response = await myService.sendRequest("/ticket", { data: "body" });

sinon.assert.calledWith(spy, {
headers: {
"API-TOKEN": myService.token
},
body: { data: "body" },
json: true,
url: "https://my-service.com/private/api/ticket"
});

response.should.deep.equal({ id: "the-id" });

spy.restore();
});
});

Example 2: test an async function throws #

The trick here is to throw an exception if doesn't fail:

it("throws an exception if ticket data is not valid", done => {
myApi
.createSupportTicket({
requestor: "ada@lovelace.com",
description: "Out of steam"
})
.then(() => {
throw new Error("was not supposed to succeed.");
})
.catch(error => {
error.details[0].message.should.eq('"category" is required');
done();
});
});

🖖