草庐IT

node.js - Mocha 路由测试不异步执行

coder 2023-10-28 原文

我已经开始使用 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 )是所有用户路由的 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() 函数,但它仍然不起作用。

最佳答案

在测试套件中链接 super 测试请求的方式存在问题 - 第二个请求未正确调用。当您没有清除数据库时,测试在第一个 .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);

        });
   });
});

关于node.js - Mocha 路由测试不异步执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26727007/

有关node.js - Mocha 路由测试不异步执行的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  3. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  4. ruby - 使用 C 扩展开发 ruby​​gem 时,如何使用 Rspec 在本地进行测试? - 2

    我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当

  5. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  6. ruby - Ruby 的 Hash 在比较键时使用哪种相等性测试? - 2

    我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。

  7. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  8. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  9. ruby - Sinatra:运行 rspec 测试时记录噪音 - 2

    Sinatra新手;我正在运行一些rspec测试,但在日志中收到了一堆不需要的噪音。如何消除日志中过多的噪音?我仔细检查了环境是否设置为:test,这意味着记录器级别应设置为WARN而不是DEBUG。spec_helper:require"./app"require"sinatra"require"rspec"require"rack/test"require"database_cleaner"require"factory_girl"set:environment,:testFactoryGirl.definition_file_paths=%w{./factories./test/

  10. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

随机推荐