TransWikia.com

How to test an express API endpoint on a failing condition, using jest and supertest?

Stack Overflow Asked by kob003 on January 20, 2021

I have a endpoint(/api/users/) which registers a user.
It shows error if the conditons on ‘name’, ’email’ and ‘password’ are not met, which are set by express-validator.

This is my user.js:

    import bcrypt from "bcryptjs";
    import { body, validationResult } from "express-validator";
    import jwt from "jsonwebtoken";
    import util from "util";
    import auth from "../../middleware/auth";
    import User from "../../models/User";   
    const express = require("express");
    const router = express.Router(); 

    router.post(
         "/",
          [
            body("name", "Name is required").not().isEmpty(),
            body("email", "Please enter a valid email").isEmail(),
            body(
              "password",
              "Please enter a password of length greater than 6"
            ).isLength({ min: 6 }),
          ],
          async (req, res) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
              return res.status(400).json({ errors: errors.array() });
            }
            const { name, email, password } = req.body;
            try {    
              let user = await User.findOne({ email });
          if (user) {
            return res
              .status(400)
              .json({ errors: [{ msg: "User already exists" }] });
          }
          const avatar = gravatar.url(email, {
            s: "200",
            r: "pg",
            d: "mp",
          });

      user = new User({
        name,
        email,
        avatar,
        password,
      });

      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(password, salt);
      user.password = hashedPassword;

      await user.save();
      const payload = {
        user: {
          id: user.id,
        },
      };
      const jwttoken = process.env.JWT_TOKEN;
      const signIn = util.promisify(jwt.sign);
      const token = await signIn(payload, jwttoken, { expiresIn: 360000 });
      res.json({ token });
    } catch (err) {
      console.error(err.message);
      res.status(500).send("server Error");
    }
  }
);

module.exports = router;

Now i want to test(i am using jest) on this endpoint to pass the fail condtion i.e if user doesn’t enters ‘name’ or password’s length is less than 6 etc., as provided in the express validator.
I tried doing this.

This is my user.test.js:

    import app from "../../app";
    import supertest from "supertest";
    import User from "../../models/User";
    const request = supertest(app);

    beforeEach(async () => {
      await User.deleteMany({});
    });

    test("user fails to register", async () => {
      expect.assertions(1);
      try {
        await request.post("/api/users").send({
          name: "",
          email: "",
          password: "",
        });
      } catch (err) {
        expect(err).toEqual({
          errors: [
            "Name is required",
            "Please enter a valid email",
            "Please enter a password of length greater than 6",
          ],
        });
      }
    });

I am getting the following error:

Expected one assertion to be called but received zero assertion calls.

What am i doing wrong?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP