8

テストを実行すると、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)
4

1 に答える 1

7

記述をネストできますが、テストはネストできません。各テストはスタンドアロンであることを意図しているため、結果を確認すると、失敗した場所 (保存時またはユーザー名プロパティがない) を確認できます。たとえば、上記のコードでは、done() がないため、「エラーなしで保存する必要がある」テストに失敗する方法はありません。これは、上記のコードがタイムアウトする理由でもあります。mocha は、「エラーなしで保存する必要がある」テストの done() を見つけることができません。

ただし、説明をネストできることは非常に強力です。各記述内には、before、beforeEach、after、および afterEach ステートメントを含めることができます。これらを使用すると、上記で試みているネスティングを実現できます。これらのステートメントを読みたい場合は、詳細について mocha docs を参照してください。

あなたが達成しようとしていることを私が書く方法は次のとおりです:

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();
      });
    });
  });
});
于 2012-11-10T12:00:05.530 に答える