Search code examples
javascriptmocha.jssinonsinon-chai

Sinon stub function parameter


I have an express app with a router I would like to test with Sinon. I'm not successful in mocking the response parameter that is passed into the request handler and would like some help.

export const pingHandler = (request, response, next) => {
    response.status(200).send('Hello world');
}

This is my current test setup using Mocha, Sinon, Chai & sinon-chai. fakeRes.status was never called as expected.

describe("pingHandler", () => {
    it("should return 200", async () => {
        const fakeResponse = {
            status: sinon.fake(() => ({
                send: sinon.spy()
            }))
        };
        pingHandler({}, fakeResponse, {});
        expect(fakeResponse.status).to.have.been.called;
        // => expected fake to have been called at least once, but it was never called
    });
});

Solution

  • Here is the unit test solution:

    index.ts:

    export const pingHandler = (request, response, next) => {
      response.status(200).send('Hello world');
    }
    

    index.spec.ts:

    import { pingHandler } from "./";
    import sinon from "sinon";
    
    describe("pingHandler", () => {
      it("should return 200", () => {
        const mRes = {
          status: sinon.stub().returnsThis(),
          send: sinon.stub(),
        };
    
        pingHandler({}, mRes, {});
        sinon.assert.calledWith(mRes.status, 200);
        sinon.assert.calledWith(mRes.send, "Hello world");
      });
    });
    

    Unit test result with 100% coverage:

     pingHandler
        ✓ should return 200
    
    
      1 passing (8ms)
    
    ---------------|----------|----------|----------|----------|-------------------|
    File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    ---------------|----------|----------|----------|----------|-------------------|
    All files      |      100 |      100 |      100 |      100 |                   |
     index.spec.ts |      100 |      100 |      100 |      100 |                   |
     index.ts      |      100 |      100 |      100 |      100 |                   |
    ---------------|----------|----------|----------|----------|-------------------|