gpt4 book ai didi

node.js - 如何 stub 在另一个方法中间接调用的方法

转载 作者:行者123 更新时间:2023-11-28 21:21:03 24 4
gpt4 key购买 nike

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

我的代码:

//测试.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);

//用户 Controller .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.connectorUsersController 模块中的 api.db.connector

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

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

关于node.js - 如何 stub 在另一个方法中间接调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51592133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com