简体   繁体   中英

How to mock response of getPass function

Hello I am writing a unit test case of my javascript function. I am using mocha, Chai, expect, sinon

app.js

module.exports = {
    saveInGlobal: async () => {
      try {
        if (global.pass !== null && global.pass !== '') {
          return module.exports.getpass().then((res) => {
            return global.pass = res;
          });
        }
      } catch (err) {

      }
    },
    getPass: async () => {
       return "test";
    } 
}

I want to mock the getPass() function and then assert global.pass . Can anyone suggest how to mock the getPass() here using sinon

The basic functionality is provided by sinon.stub() which overrides some property in object - in your case module.getPass :

const theModule = require('theModule'); // module with getPass
it('foo', () => {
    // Prepare
    const getPassStub = sinon.stub(theModule, 'getPass');
    getPassStub.resolves('mocked');
    // Act

    // call your code here

    // Assert
    expect(getPassStub.calledOnce).to.be.true;
    getPassStub.restore()
});

This works, but only if your test passes. In case of failure, stub survives ( restore is not called) and getPass remains mocked for rest of test execution.

Consider using: after(() => module.getPass.restore()) or more preferably using sinon.Sandbox .

Stub doc: http://sinonjs.org/releases/v4.5.0/stubs/

Sandbox doc: http://sinonjs.org/releases/v4.5.0/sandbox/

You can't use try/catch with asynchronous code( promise.then ). So I remove it. Here is the unit test:

app.js :

module.exports = {
  saveInGlobal: async () => {
    if (global.pass !== null && global.pass !== "") {
      return module.exports.getPass().then((res) => {
        return (global.pass = res);
      });
    }
  },
  getPass: async () => {
    return "test";
  },
};

app.test.js :

const app = require("./app");
const sinon = require("sinon");
const { expect } = require("chai");

describe("49858991", () => {
  afterEach(() => {
    sinon.restore();
  });
  describe("#saveInGlobal", () => {
    it("should save in global", async () => {
      global.pass = "a";
      const getPassStub = sinon.stub(app, "getPass").resolves("mock value");
      await app.saveInGlobal();
      sinon.assert.calledOnce(getPassStub);
      expect(global.pass).to.be.eq("mock value");
    });

    it("should do nothing", async () => {
      global.pass = null;
      const getPassStub = sinon.stub(app, "getPass").resolves("mock value");
      await app.saveInGlobal();
      sinon.assert.notCalled(getPassStub);
      expect(global.pass).to.be.eq(null);
    });
  });

  describe("#getPass", () => {
    it('should return "test"', async () => {
      const actual = await app.getPass();
      expect(actual).to.be.eq("test");
    });
  });
});

Unit test results with 100% coverage:

 49858991
    #saveInGlobal
      ✓ should save in global
      ✓ should do nothing
    #getPass
      ✓ should return "test"


  3 passing (16ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/49858991

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM