【问题标题】:How to pass next as an argument on Mocha test如何通过 next 作为 Mocha 测试的参数
【发布时间】:2020-10-26 12:10:43
【问题描述】:

我正在尝试测试一个函数,该函数检查用户是否输入了电子邮件,如果是,则返回 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;
    })
});

【问题讨论】:

    标签: express testing mocha.js


    【解决方案1】:

    当你调用函数时,你应该为next传递一个模拟,它可以像传递一样简单:

    () => {} 或任何其他模拟(使用 jest/sinon/etc),取决于您想要的行为。

    所以改变:

    expect(authController.checkIfEmailExists("email@email.com")).to.be.true;
    

    到:

    expect(authController.checkIfEmailExists("email@email.com", () => {})).to.be.true;
    

    此外,您似乎正在将中间件与应用逻辑混合:您没有向我们展示 checkIfEmailExists() 的外观,我认为没有任何充分的理由传递 next

    如果它是一个中间件,它应该被称为中间件(来自路由),而不是像这里那样明确地调用它。

    【讨论】:

    • @Chris 你不能在抛出错误的同时返回false。您必须选择或。这不是一个中间件,所以你不应该传入next - 为什么不只是return false?你想通过调用next(new throwsAnError("Συμπληρώστε το e-mail", 400)); 来完成什么?
    猜你喜欢
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2015-07-28
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多