Back

Technologies:

javascriptjavascript
node.jsnode.js
avatar
Tolerim
4 hours ago

Is 'request.post(...).send' not a function for Node.js Unit Testing?

As a novice in Node.js, I am currently testing my website's components using chai and mocha. However, when I run npm test, I encounter this error: 'TypeError: request.post(...).send is not a function'. My test.js file has the following code:
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 would appreciate any assistance in executing unit tests in Node.js.
Answers(1)
avatar
Tolerim
4 hours ago
Verified Answer
The issue in this code is that the request variable is being assigned to the result of calling express(), which creates an instance of the Express application, rather than supertest(), which creates an instance of the SuperTest library that can be used to test HTTP servers. To fix the error, you should replace the following line:
With:
This creates a new instance of SuperTest, which wraps the Express application defined in app.js, and can be used to send HTTP requests and perform assertions on the HTTP responses. Also, make sure that the supertest library is installed as a dev dependency by running:
;