node.js – Mocha路由测试不是异步执行的

我已经开始使用mocha了,我对一个特定的测试用例有疑问.这是代码:

var assert = require("chai").assert;
var request = require('supertest');
var http = require("http");
var conf = require("../config/config");
var app = require("../app");
var mongoose = require('mongoose');
var User = mongoose.model('User');

describe('User controller', function(){
  describe('POST /register', function(){
     it('should return false when the parameters are not unique', function (done) {
        request(app)
           .post('/user/register')
           .send({username:"janette_doe", email:"janette_doe@gmail.com", password:"test123"})
           .expect('Content-Type',/json/)
           .expect({success:true, redirect:'/user/registerConfirmation'})
           .end(function(err, res) {
              if (err) {
                 return done(err);
              }

              request(app)
                 .post('/user/register')
                 .send({username:"janette_doe", email:"janette_doe@gmail.com", password:"test123"})
                 .expect('Content-Type',/json/)
                 .expect({success:false}, done);
     });
  });
});

我期望结果是错误的,因为在数据库中插入用户之后,唯一索引规则应该引发错误.当我运行这个测试时,我得到了这个:{success:true,redirect:’/ user / registerConfirmation’},我应该得到这个:{success:false}.我注意到,当我在每次测试之前没有清除数据库时(在utils.js中),我得到了预期的值.由于异步错误,我是否收到此错误?我怎样才能重写这个测试以确保它有效?

谢谢

util.js包含测试序列的配置:

'use strict';

process.env.NODE_ENV = 'test';

var config = require('../config/config');
var mongoose = require('mongoose');

beforeEach(function (done) {

    mongoose.connection.db.dropDatabase();

    return done();
});

afterEach(function (done) {
    return done();
});

user.js用户模型:

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,

var UserSchema = new Schema({
    username: {type: String, required: true, unique: true},
    email: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    status: {type: Number, default:0}
});

UserSchema.virtual('date')
    .get(function(){
        return this._id.getTimestamp();
});

UserSchema.pre('save', function(next) {
    //Password encryption ...
});

mongoose.model('User', UserSchema);

user.js(controller)是所有用户路由的控制器.

...

router.post('/register', function (req,res,next){
    var newUser = new User({
        username: req.body.username
        , email: req.body.email
        , password: req.body.password
    });

    newUser.save(function(err){
        if(err){
            res.send({success: false});
        }else{
            var newToken = new UserToken({
                userId: newUser._id
                , email: newUser.email
            });

            newToken.save(function(err){
                if(err){
                    res.send({success: false});
                }else{
                    res.send({success: true, redirect: '/user/registerConfirmation'});
                }
            });
        }
    });
});

...

编辑

我已经尝试了end()函数,它仍然无法正常工作.

最佳答案 如何在测试测试套件中链接超级请求 – 第二个请求未正确调用.当您没有清除数据库时,测试在第一个.expect({success:true,…})上失败并且您获得了预期值.

正确的方法是使用.end方法执行第一个请求,检查潜在错误,然后执行第二个请求以查看它是否已失败:

describe('User controller', function(){
   describe('POST /register', function(){
      it('should return false when the parameters are not unique', function (done) {
        request(app)
        .post('/user/register')
        .send({username:"janette_doe", email:"janette_doe@gmail.com", password:"test123"})
        .expect('Content-Type',/json/)
        .expect({success:true, redirect:'/user/registerConfirmation'})
        .end(function(err, res) {

            // Check if first request has failed (it should not!)
            if (err) {
               return done(err);
            }

            // Testing the second, not unique request. that should fail
            request(app)
            .post('/user/register')
            .send({username:"janette_doe", email:"janette_doe@gmail.com", password:"test123"})
            .expect('Content-Type',/json/)
            .expect({success:false}, done);

        });
   });
});
点赞