express - 如何通过 next 作为 Mocha 测试的参数
问题描述
我正在尝试测试一个函数,该函数检查用户是否输入了电子邮件,如果是,则返回 true,否则将错误参数传递给下一个函数,然后返回 false。用户通过电子邮件时的测试成功运行,但用户未提供电子邮件时的测试失败。错误日志是 next 不是函数。怎么可能将 next 作为参数传递?
const crypto = require("crypto");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const User = require("../model/userModel");
const throwsAnError = require("../utils/throwsAnError");
exports.signup = async (req, res, next) => {
const {email, username, password, confirmPassword} = req.body;
if(!checkIfEmailExists(email, next)) {
return;
}
try{
const user = await User.create({
email: email,
userName: username,
password: password,
confirmPassword: confirmPassword
});
res.status(200).json({
message: "success",
data: user
})
}
catch(e){
next(new throwsAnError("Ο χρήστης δεν μπορεί να δημιουργηθεί", 400, e));
console.log("I'm in");
}
};
function checkIfEmailExists(email, next) {
if(!email) {
next(new throwsAnError("Συμπληρώστε το e-mail", 400));
return false;
}
return true;
}
exports.checkIfEmailExists = checkIfEmailExists;
const expect = require("chai").expect;
const authController = require("../controller/authController");
describe("Testing if email exist", function() {
it("should return true if email exists", function() {
expect(authController.checkIfEmailExists("email@email.com")).to.be.true;
})
it("should return false if email does not exist", function() {
expect(authController.checkIfEmailExists(undefined, next)).to.be.false;
})
});
解决方案
当您调用该函数时,您应该传递一个模拟 for next
,它可以像传递一样简单:
() => {}
或任何其他模拟(使用 jest/sinon/etc),取决于您想要的行为。
所以改变:
expect(authController.checkIfEmailExists("email@email.com")).to.be.true;
至:
expect(authController.checkIfEmailExists("email@email.com", () => {})).to.be.true;
此外,看起来您正在将中间件与应用程序逻辑混合在一起:您没有向我们展示checkIfEmailExists()
它的外观,我看不出有什么好的理由传入next
.
如果它是一个中间件,它应该被称为中间件(来自路由),而不是像这里那样明确地调用它。
推荐阅读
- c - 学习创建自己的哈希表但遇到分段错误
- python - 如何以水平方式打印熊猫数据框列的平均值?
- azure - 可以为 ACR 存储库进行 Azure RBAC 角色分配吗?
- apache-spark - 为什么我不需要在 Databricks 中创建 SparkSession?
- javascript - Angular - 组件的动态大小未更新
- html - HTML+CSS 中的动态 3 列布局:侧列相等且最大,中间列最小并驱动布局?
- java - 将字符串转换为 2 个数字之间的唯一 ID
- r - 从数据中创建 10 个折叠,但将具有相同 ID 的 vlaues 放在同一折叠中
- python - 用于通过自定义代码访问 Smart Lock 系统的现有 API 或文档?(例如耶鲁,八月)
- python - Python 构建总是重新安装 setuptools