我有一个节点/表达了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);
}
希望,有人可以帮助我吗?
答案 0 :(得分:0)
db
是测试模块中的 couchdb.connector 和 UsersController 模块中的 api.db.connector 。
为了被存根,应该将它存根在同一db
对象上:
const db = require('../../../api/api.dbConnectors/api.db.connector');
...
const stubedReadUser = sinon.stub(db, 'readDoc');