简体   繁体   中英

Javascript sinon testing callback

I'm trying to test that certain function is called in a callback, however I don't understand how to wrap the outer function. I'm using mocha as my testing suite, with chai as my assertion library, and sinon for my fakes.

fileToTest.js

const externalController = require('./externalController');

const processData = function processData( (req, res) {
  externalController.getAllTablesFromDb( (errors, results) => {
    // call f1 if there are errors while retrieving from db
    if (errors) {
      res.f1();
    } else {
      res.f2(results);
    }
  )};
};

module.exports.processData = processData;

In the end I need to verify that res.f1 will be called if there are errors from getAllTablesFromDb, and res.f2 will be called if there are no errors.

As can be seen from this snippet externalController.getAllTablesFromDb is a function that takes a callback, which in this case I have created using an arrow function.

Can someone explain how I can force the callback down error or success for getAllTablesFromDb so that I can use a spy or a mock to verify f1 or f2 was called?

var errorSpy = sinon.spy(res, "f1");
var successSpy = sinon.spy(res, "f2");

// your function call

// error
expect(errorSpy.calledOnce);
expect(successSpy.notCalled);

// without errors
expect(errorSpy.notCalled);
expect(successSpy.calledOnce);

One possible solution is to extract the callback then force that down the desired path of failure or success. This extraction can be done using a npm package called proxyquire . The callback is extracted by removing the require line from the beginning of the file then:

const proxyquire = require('proxyquire');

const externalController = proxyquire('path to externalController',
  'path to externalController dependency', {
    functionToReplace: (callback) => { return callback }
  }
});

const extractedCallback = externalController.getAllTablesFromDb(error, results);

Then you can call extractedCallback with the parameters you want.

extractedCallback(myArg1, myArg2);

and set a spy on res.f1 and res.f2

sinon.spy(res, 'f1');

And do any assertion logic you need to.

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