首页 > 解决方案 > 如何通过 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;
    })
});

标签: expresstestingmocha.js

解决方案


当您调用该函数时,您应该传递一个模拟 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.

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


推荐阅读