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.