未捕获的AssertionError:期望{}等于“测试”

时间:2018-10-16 21:30:33

标签: node.js express mocha chai supertest

我不确定为什么要说对象为空。这是我的测试代码块。

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

  it("Creates a new user", done => {
    request(app)
      .post("/register")
      .send(body)
      .end((err, res) => {
        if (err) return done(err);
        expect(res.body).to.be.equal("testing");
        done();
      });
  });
});

测试中是否缺少某些东西来识别所传递的信息?就像在有效负载中一样,因为我认为这就是.send(payload)的目的。

感谢您的澄清。

**更新控制器和更多信息**

//测试

let request = require("supertest");
let expect = require("chai").expect;
let app = require("../../server/server");

describe("GET /test", function() {
  it("Returns a json for testing", done => {
    request(app)
      .get("/test")
      .end((err, res) => {
        done();
      });
  });
});

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

  it("Creates a new user", done => {
    request(app)
      .post("/register")
      .send(body)
      .expect(res => {
        expect(res.body).to.be.equal("testing");
      })
      .end(done);
  });
});

//用户路线

const express = require("express");
const router = express.Router();

// Load User Model
const User = require("../../models/User");

// @route GET api/users/test
// @desc Tests user route
// @access Public
router.get("/test", (req, res) => res.json({ msg: "Users Works" }));

router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      res.status(409).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 => res.status(200).send(user))
        .catch(err => console.log(err));
    }
  });
});

module.exports = router;

//服务器

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

const users = require("./routes/api/users");

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// DB Config
const db = require("../config/keys").mongoURI;

// Connect to MongoDB Atlas
mongoose.connect(
  db,
  { useNewUrlParser: true },
  (err, client) => {
    if (err) {
      console.log("Error occurred while connecting to MongoDB Atlas...\n", err);
    }
    console.log("Connected...");
  }
);

// Routes
app.use("/api/users", users);

const port = process.env.PORT || 5000;

let server = app.listen(port, () =>
  console.log(`Server running on port ${port}`)
);

module.exports = server;

0 个答案:

没有答案