我在一个 ejsnodejs 应用程序中需要测试一个函数。这个函数添加了一个用户(名字和4个字母等级的数组)。我想测试一下这个函数是否能添加一个用户。
该函数。
router.addUsers = (req, res) => {
console.log("in homeController addUser");
var newUserName = req.body.name;
console.log("name " + newUserName);
var newUsergrade = req.body.grade;
var temp = 0;
newUsergrade.forEach(letter => {
letter = letter.toUpperCase();
switch (letter) {
case 'A':
letter = 4.0
break
case 'A-':
letter = 3.7
break
case 'B+':
letter = 3.3
break
case 'B':
letter = 3.0
break
case 'B-':
letter = 2.7
break
case 'C+':
letter = 2.3
break
case 'C':
letter = 2.0
break
case 'C-':
letter = 1.7
break
case 'D+':
letter = 1.3
break
case 'D':
letter = 1.0
break
case 'F':
letter = 0.0
break
}
temp += letter;
});
var valid = false;
if (temp / 4 >= 2.5) {
valid = true;
} else {
vaild = false;
}
col.insertOne({
name: newUserName,
grade: newUsergrade,
isValid: valid
}, function(err, r) {
test.equal(null, err);
test.equal(1, r.insertedCount);
col.find({}).toArray((err, userData) => {
console.log("record found: ", userData);
usersArray = userData;
});
});
usersArray.push({
name: newUserName
});
res.render("users", {
allUsers: usersArray,
title: "Users List"
});
};
到目前为止,我一直在尝试
describe("addUsers", () => {
it("should make sure a user can be added to the array", () => {
var usersArray = {
name: "blake",
grade: ["a", "a", "b", "d"]
};
expect(router.addUsers(usersArray)).to.deep.include({
name: "blake",
grade: ["a", "a", "b", "d"]
});
});
it("should return an empty object with empty request body input", () => {
var emptyBody = {};
expect(router.addUsers(emptyBody)).to.deep.include({});
});
});
我收到了一个错误信息 'name' is undefined. 这可能是由于req,res或res.render的原因吗?
expect(router.addUsers(usersArray)).to.deep.include({
name: "blake",
grade: ["a", "a", "b", "d"]
});
你的函数返回未定义,但这里你要检查返回值是否包括name。这就是为什么它说name是未定义的。
你要的是下面这样的东西,你可以使用某种包来更恰当地模拟请求和响应对象。
const fakeReq = { body: { name: 'something', grade: 'somethingElse' }},
fakeRes = { render: () => {}};
await router.addUsers(fakeReq, fakeRes);
expect(usersArray).to.deep.include({ name: 'something' });