4

So, I've never actually implemented any testing in the past in all my projects and decided to start implementing it in a new project I'm working on. As a total beginner I'm a bit confused with the output I'm getting.

When I'm using Postman. It isn't returning a 500 error but instead saving the information to the backend. The error I'm getting when running test is

1) POST /users
       Creates a new user:
     Error: expected 200 "OK", got 500 "Internal Server Error"

I'll also show what my code looks like in order to hopefully find out where I'm going wrong.

// Testing

var express = require("express");
var request = require("supertest");
var app = express();
let router = require("../../server/routes/api/users");

app.use(router);

describe("GET /test", function() {
  it("Returns a json for testing", function(done) {
    request(app)
      .get("/test")
      .set("Accept", "application/json")
      .expect("Content-Type", /json/)
      .expect(200, done);
  });
});

describe("POST /users", () => {
  let data = {
    name: "dummy",
    email: "dummy@dummy.com",
    password: 123456
  };

  it("Creates a new user", done => {
    request(app)
      .post("/register")
      .send(data)
      .set("Accept", "application/json")
      .expect("Content-Type", "text/html; charset=utf-8")
      .expect(200)
      .end(err => {
        if (err) return done(err);
        done();
      });
  });
});

// User Route file

router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      res.json({ msg: "User exist" });
    } else {
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        password: req.body.password
      });

      newUser
        .save()
        .then(user => console.log(user))
        .catch(err => console.log(err));
    }
  });
});

// User mongoose Model file

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model("users", UserSchema);

If there is something else I am missing that you'll like to see please feel free to ask and looking forward to gaining a better understanding of testing.

Yama
  • 401
  • 1
  • 8
  • 22
  • 2
    Usually a 500 error from express where you are not doing explicit error handling yourself comes from express' internal error handling when it encounters an error in the code that is uncaught. A good way to debug those errors is to place `try...catch` blocks around sections of code that you think should work. For example, wrapping the `User.findOne` call in a try...catch and then a `console.log(err)` in the catch block. This may not be the source of the issue, but it may help you track down the problem or eliminate it from a list of potential sources. – JayReardon Oct 16 '18 at 18:28
  • 1
    @JayReardon Thanks for replying. I'll update my code but that is the strange part. I don't run into a 500 internal error when using Postman and see data being sent to MongoDB Atlas. But when I run my test it says it returns a 500 instead of a 200. – Yama Oct 16 '18 at 18:38
  • I agree that it is odd; however, there could be circumstances to normal server run (when you connect to it with Postman) that are different when you are attempting the unit test with `supertest` and the purpose of the `try...catch` blocks are to help identify what those might be. We use `supertest` in very much the same fashion with our ExpressJS projects that you are and the strategy I've described helped us identify setup issues with our unit testing. – JayReardon Oct 16 '18 at 18:46

1 Answers1

6

The response expected by the POST test is not matching the response send by the server. In POST test change 200 to 500 and display the response, then you will see the response expected and response sent by the server, and hence then can compare the two and make changes. Somewhat like this ---

 describe("POST /users", () => {
  let data = {
    name: "dummy",
    email: "dummy@dummy.com",
    password: 123456
  };

  it("Creates a new user", done => {
    request(app)
      .post("/register")
      .send(data)
      .set("Accept", "application/json")
      .expect("Content-Type", "text/html; charset=utf-8")
      .expect(response => {console.log(response)})
      .expect(500, done);
  });
});

now compare what is expected and what is sent by the server. And make changes in your code(in the response received by the test ,as most of the time it is the object/document id in database collection as it comes with the response),

Do not forget to change 500 back to 200 and proceed with changes.

sebastian
  • 2,386
  • 26
  • 22
neelesh bisht
  • 640
  • 8
  • 13