skip to Main Content

I am beginning to test the components of my node.js website using chai and mocha, but when I run npm test I get this error:

‘ TypeError: request.post(…).send is not a function’

This is the code in my test.js file:

    const chai = require("chai");
const expect = chai.expect;
const app = require("./app.js");
const express = require("express");
const request = express();

describe("POST /register", () => {
  it("should register a new user and redirect to login page", (done) => {
    const user = {
      email: "[email protected]",
      username: "johndoe",
      password: "password",
      userType: "user"
    };
    request.post("/register")
      .send(user)
      .end((err, res) => {
        expect(res.status).to.equal(302);
        expect(res.header.location).to.equal("/login");
        done();
      });
  });
});

I am new to Node.js so I’m still understanding how unit tests are executed. any help would be a appreciated

2

Answers


  1. request is an Express router object. Rather than sending a request, request.post("/register") registers a path on that router.

    What you actually want to do is send a request. Because Express is for creating servers, not sending requests, you’ll have to use a different library. It seems that your code is trying to use supertest, which is a testing library that does send requests.

    To use supertest instead, first install it with npm i supertest, then change

    const request = express();
    

    in your code to

    const request = require('supertest');
    
    Login or Signup to reply.
  2. Its likely because request is an instance of express() rather than a request library like supertest.

    To fix this, you can replace request.post("/register") with a request using the supertest library like this:

    const request = require("supertest");
    const app = require("./app.js");
    
    describe("POST /register", () => {
      it("should register a new user and redirect to login page", (done) => {
        const user = {
          email: "[email protected]",
          username: "johndoe",
          password: "password",
          userType: "user"
        };
        request(app)
          .post("/register")
          .send(user)
          .end((err, res) => {
            expect(res.status).to.equal(302);
            expect(res.header.location).to.equal("/login");
            done();
          });
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search