Mocking Auth Middleware Jest

Viewed 25

hope you're doing well.

I have an endpoint I want to test that requires authentication using JWT (auth middleware). I tried to mock the function, but no result for now.

This is the route I want to test

router.post("", auth, async (req, res) => {
    const newSkill = new Skill({
        skill: req.body.skill,
        position: req.body.position,
        visibility: req.body.visibility,
        icon: req.body.icon,
    });

    try {
        await newSkill.save();
        res.status(201).send(newSkill);
    } catch (e) {
        res.status(400).send();
    }
});

This is my auth function:

const jwt = require("jsonwebtoken");
const Admin = require("../models/admin");

const auth = async (req, res, next) => {
    try {
        const token = req.header("Authorization").replace("Bearer ", "");

        const decoded = jwt.verify(token, process.env.JWT_SECRET);

        const admin = await Admin.findOne({
            _id: decoded._id,
            "tokens.token": token,
        });

        if (!admin) {
            throw new Error();
        }

        req.admin = admin;
        next();
    } catch (e) {
        res.status(401).send({ error: "Please Authenticate." });
    }
};

module.exports = auth;
0 Answers
Related