如何存根在另一个方法中间接调用的方法

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

我有一个节点/express REST API。 为了测试我的 UsersController.login 方法,它将间接调用 dbConnector.readDoc() 函数,我需要存根它。 但是我没有成功。永远不会调用存根。

我的代码:

//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 路线

// 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);
}

希望有人能帮助我?

db 在测试模块中是 couchdb.connectorapi.db.connectorUsersController 模块。

为了被存根,它应该在同一个 db 对象上存根:

const db = require('../../../api/api.dbConnectors/api.db.connector');
...
const stubedReadUser = sinon.stub(db, 'readDoc');