lundi 30 juillet 2018

How to stub a method that is indirectly called inside another method

I've a node / express REST API. To test my UsersController.login method, that will indirectly call dbConnector.readDoc() function, I need to stub it. But I've not been succeeded. The stub is never called.

My Code:

//test.spec.js

  const db = require('../../../api/api.dbConnectors/couchdb.connector');

  it('STUB should return 404 Error response if NON EXISTING username on DB (passw irrelevant)', function () {
      var req = httpMocks.createRequest({
          body: {
              username: "undefUsername",
              password: 'irrelevant'
          }
      });
      var res = httpMocks.createResponse({
        locals: {
          statusCode: 404,
          message: 'Request failed with status code 404',
        }
      });

  const stubedReadUser = sinon.stub(db, 'readDoc');
  // override behavior
  stubedReadUser.rejects();
  // const p = stubedReadUser.rejects(res);
  UsersController.userLogin(req, res);
  expect(stubedReadUser).to.have.been.calledOnce;

  stubedReadUser.restore();
});

// api route

// FullPATH: /api/v1/users/...
// req.body = {username + password}
router.post('/login', UsersController.userLogin);

// UsersController.js

const db = require('../api.dbConnectors/api.db.connector');

function userLogin(req, res) {
  let user;
  let token;

  if (!ctrlHelpers.requestHasCredentials(req.body)) {
    return res.status(400).json({
      status: 400,
      message: 'Login failed: Bad request!',
    });
  }

  const userID = CONFIG.APP.USERS_NAMESPACE + req.body.username;
  db.readDoc('users', userID)
    .then((resp) => {
      // on success do something ...
    })
    .catch((err) => {
      return res.status(err.response.status).json({
        status: err.response.status,
        message: err.message,
      });
    });
}

// api.db.connector.js

// in the future will serve to select from MongoDB or CouchDB

const driver = require('./couchdb.connector');

module.exports = {
  createDoc: driver.createDoc,
  readDoc: driver.readDoc,
  updateDoc: driver.updateDoc,
  deleteDoc: driver.deleteDoc,
};

// couchdb.connector.js

module.exports = {
  readDoc,
  updateDoc,        
  (…)
};

async function readDoc(collection, docID) {
  const queryOptions = '?include_docs=true';
  const query = `${collection}${docID}${queryOptions}`;

  return axios.get(query);
}

Hope, someone could help me?

Aucun commentaire:

Enregistrer un commentaire