How does promise test with mocha and sinon?

question title

how to test promise? with mocha/chai and sinon

problem description

suppose you encapsulate a function that initiates an asynchronous request task, succeeds in executing onSuccess, and fails to execute onError. At the same time, in order to prevent asynchronous tasks from relying on the external environment, use sinon to do Substitute. Does this situation require writing test code, and if so, how?

related codes

// 
// onSuccessonError
module.exports = function (onSuccess, onError) {
  var p = new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve("ok")
    }, 1000)
  })

  p.then(function (response) {
    onSuccess(response)
  }).catch(function (error) {
    onError(error)
  })
}
Apr.07,2021

mocha already supports asynchronism. Here is the reference code

var myModule = require('../') //
describe('myModule', function () {
    it('onSuccess', function (done) {
        myModule(function(){done()},function(){done('')});
    }
    it('onError', function (done) {
        myModule(function(){done('')},function(){done()});
    }
}

main.js :

module.exports = function(onSuccess, onError) {
  var p = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('ok');
    }, 1000);
  });

  p.then(function(response) {
    onSuccess(response);
  }).catch(function(error) {
    onError(error);
  });
};

main.test.js :

const request = require('./main');
const sinon = require('sinon');

const flushPromises = () => new Promise(setImmediate);

describe('1010000015955091', () => {
  let clock;
  before(() => {
    clock = sinon.useFakeTimers({ toFake: ['setTimeout'] });
  });
  after(() => {
    clock.restore();
  });
  it('should success', async () => {
    const onSuccessStub = sinon.stub();
    const onErrorStub = sinon.stub();
    request(onSuccessStub, onErrorStub);
    clock.tick(1000);
    await flushPromises();
    sinon.assert.calledWithExactly(onSuccessStub, 'ok');
  });
});

Unit Test results + Test coverage report:

  1010000015955091
     should success


  1 passing (11ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line -sharps 
----------|---------|----------|---------|---------|-------------------
All files |   85.71 |      100 |      80 |   85.71 |                   
 main.js  |   85.71 |      100 |      80 |   85.71 | 11                
----------|---------|----------|---------|---------|-------------------

there is no reject part of promise in your code, so it is always resolve , only the test cases of successful callback function

.
Menu