所以我正在开发一个 express.js 应用程序,其中我有一个 Mongoose 模型用户。我编写了一个测试文件(使用 Mocha)来测试 save() 函数,但我所有的测试执行时间太长,最终超时。
这是我遇到的错误:
Testing - Server - User - Model
Testing save()
1) should be able to save without problems
2) should fail to save an exisitng user again
3) should should an error when try to save with empty email
4) should give an error when try to save with empty password
5) "after all" hook
0 passing (8s)
5 failing
1) Testing - Server - User - Model Testing save() should be able to save without problems:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:159:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
2) Testing - Server - User - Model Testing save() should fail to save an exisitng user again:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:159:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
3) Testing - Server - User - Model Testing save() should should an error when try to save with empty email:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:159:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
4) Testing - Server - User - Model Testing save() should give an error when try to save with empty password:
Uncaught AssertionError: expected null to exist
at Promise.<anonymous> (/Users/Mukul/PersonalProjects/ResourceBucket/test/models/user.server.model.test.js:69:12)
at Promise.<anonymous> (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/mpromise/lib/promise.js:177:8)
at Promise.emit (events.js:98:17)
at Promise.emit (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/mpromise/lib/promise.js:84:38)
at Promise.fulfill (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/mpromise/lib/promise.js:97:20)
at handleSave (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/model.js:133:13)
at /Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/utils.js:408:16
at model.save (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/model.js:222:7)
at model._done (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/hooks/hooks.js:59:24)
at _next (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/hooks/hooks.js:52:28)
at fnWrapper (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/hooks/hooks.js:159:8)
at model.<anonymous> (/Users/Mukul/PersonalProjects/ResourceBucket/models/user.js:22:46)
at _next (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/hooks/hooks.js:50:30)
at fnWrapper (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/node_modules/hooks/hooks.js:159:8)
at complete (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/document.js:992:5)
at /Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/document.js:983:20
at ObjectId.SchemaType.doValidate (/Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/schematype.js:603:22)
at /Users/Mukul/PersonalProjects/ResourceBucket/node_modules/mongoose/lib/document.js:974:9
at process._tickCallback (node.js:442:13)
5) Testing - Server - User - Model "after all" hook:
Error: timeout of 2000ms exceeded
at null.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:159:19)
at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
这是我的测试文件:
// Module dependencies
var should = require("should");
var mongoose = require("mongoose");
var config = require('../../config/config');
var nodemailer = require('nodemailer');
var bcrypt = require('bcryptjs');
// Get User model
var User = require('../../models/user')(mongoose, config, bcrypt, nodemailer).User;
// Define global test variables
var user;
var user2;
// Unit tests
describe('Testing - Server - User - Model', function(){
// Since its before - it happens once ONCE before ALL the tests
before(function(done){
// Since we're using the global variables don't use var in front of them
user = new User({
email: 'a@a.com',
password: 'a'
});
// Another user with same details as the first user cos
// For a test case, where we try to insert 2 records with same details (should fail as exprected)
user2 = new User({
email: 'a@a.com',
password: 'a'
});
done();
});
// Testing function #1 - save()
describe('Testing save()', function(){
// Test case #1 - save normally
it('should be able to save without problems', function(done){
try {
user.save(done);
} catch (x) {
done(x);
}
});
// Test case #2 - should fail to save an exisitng user again
it('should fail to save an exisitng user again', function(done){
user.save(function(){
user2.save(function(err){
should.exist(err);
done();
});
});
})
// Test case #3 - should give an error when try to save with empty email
it('should should an error when try to save with empty email', function(done){
user.email = '';
return user.save(function(err){
should.exist(err);
done();
});
});
// Test case #4 - should give an error when try to save with empty password
it('should give an error when try to save with empty password', function(done){
return user.save(function(err){
should.exist(err);
done();
});
});
});
after(function(done){
User.remove().exec(done);
});
});
这是我的用户模型文件:
module.exports = function(mongoose, config, bcrypt, nodemailer){
// User schema
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: {
type: String,
select: false
}
});
// Makes sure that our passwords are always hashed before saving to the database
// Refer to sessionBuddy's resources for more info on this
userSchema.pre('save', function(next) {
var user = this;
// Only hash the password if its modified or new
if (!user.isModified('password')) return next();
// Generate salt
bcrypt.genSalt(config.SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password along with the salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// overwrite the cleartext password with the hashed one
user.password = hash;
next();
});
});
});
// Password verification for cleartext and hashed passwords
userSchema.methods.comparePassword = function(password, done) {
bcrypt.compare(password, this.password, function(err, isMatch) {
done(err, isMatch);
});
};
var User = mongoose.model('User', userSchema);
return{
User : User
}
}
我还尝试了 try/catch 方法来获取来自该线程的 promise :In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded.但这也没有用。
感谢任何帮助! 谢谢
编辑:正如评论中所建议的,我没有连接到测试文件中的数据库。 EDIT2:现在在最后 2 个测试中出现以下错误 - “Uncaught AssertionError: expected null to exist” EDIT3:实际上我的模式可以将“电子邮件”和“密码”保存为空,因为我没有将必填字段设置为真,更新我的模式后,它可以工作。
最佳答案
正如评论中所指出的,您实际上并没有连接到 mongodb 数据库。您的所有请求都将由 Mongoose 排队,并且在您连接到数据库之前永远不会执行(从而在您的测试中产生超时)。
编辑 至于你的第二个问题,当它实际上没有产生任何错误时,你期望错误存在。此行未通过您的测试:
should.exist(err);
您应该检查您的模型。在您的第三个测试用例中,您要求用户拥有电子邮件,但您的模型并未强制执行。密码也一样。 此外,您不会在测试中将密码设为空。
关于node.js - Mocha 测试执行时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890761/
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
我在使用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
我正在编写一个包含C扩展的gem。通常当我写一个gem时,我会遵循TDD的过程,我会写一个失败的规范,然后处理代码直到它通过,等等......在“ext/mygem/mygem.c”中我的C扩展和在gemspec的“扩展”中配置的有效extconf.rb,如何运行我的规范并仍然加载我的C扩展?当我更改C代码时,我需要采取哪些步骤来重新编译代码?这可能是个愚蠢的问题,但是从我的gem的开发源代码树中输入“bundleinstall”不会构建任何native扩展。当我手动运行rubyext/mygem/extconf.rb时,我确实得到了一个Makefile(在整个项目的根目录中),然后当
我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的: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?并散列所有无济于事。
我有一些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
我遵循了教程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
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/
我遵循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
我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r
我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查