我应该如何使用摩卡和mongoose?

运行testing时,我一直在save()方法中发生错误。

var User = require('../../models/user') , should = require('should'); describe('User', function(){ describe('#save()', function(){ it('should save without error', function(done){ var user = new User({ username : 'User1' , email : 'user1@example.com' , password : 'foo' }); user.save(function(err, user){ if (err) throw err; it('should have a username', function(done){ user.should.have.property('username', 'User1'); done(); }); }); }) }) }) 

这里是错误的:

 $ mocha test/unit/user.js ․ ✖ 1 of 1 test failed: 1) User #save() should save without error: Error: timeout of 2000ms exceeded at Object.<anonymous> (/usr/local/lib/node_modules/mocha/lib/runnable.js:1 61:14) at Timer.list.ontimeout (timers.js:101:19) 

你可以嵌套描述但不是testing。 每个testing都是独立的,因此当您查看结果时,您可以看到失败的位置 – 保存或不具有用户名属性。 例如,在上面的代码中,没有任何方法可以使'不保存错误'testing失败,因为没有完成()。 这也是上面的代码超时的原因:摩卡无法find“应该保存没有错误”testing的done()。

能够嵌套描述是非常强大的。 在每个描述中,你可以有一个before,beforeEach,after和afterEach语句。 有了这些,你可以实现你在上面尝试的嵌套。 如果您想阅读这些陈述,请参阅摩卡文档了解更多信息。

我将写你想要实现的方式如下:

 var User = require('../../models/user') , should = require('should') // this allows you to access fakeUser from each test , fakeUser; describe('User', function(){ beforeEach(function(done){ fakeUser = { username : 'User1' , email : 'user1@example.com' , password : 'foo' } // this cleans out your database before each test User.remove(done); }); describe('#save()', function(){ var user; // you can use beforeEach in each nested describe beforeEach(function(done){ user = new User(fakeUser); done(); } // you are testing for errors when checking for properties // no need for explicit save test it('should have username property', function(done){ user.save(function(err, user){ // dont do this: if (err) throw err; - use a test should.not.exist(err); user.should.have.property('username', 'User1'); done(); }); }); // now try a negative test it('should not save if username is not present', function(done){ user.username = ''; user.save(function(err, user){ should.exist(err); should.not.exist(user.username); done(); }); }); }); });