1

Mocha、Sinon、および SuperTest を使用したかなり単純なテストがあります。

describe('POST /account/register', function(done) {

    beforeEach(function(done) {
        this.accountToPost = {
            firstName: 'Alex',
            lastName: 'Brown',
            email: 'a@b.com',
            password: 'password123'
        };

        this.email = require('../../app/helpers/email');
        sinon.stub(this.email, 'sendOne')

        done();
    });

    afterEach(function(done){
        this.email.sendOne.restore();
        done();
    })

    it('sends welcome email', function(done) {

        request(app)
            .post('/account/register')
            .send(this.accountToPost)
            .expect(200)
            .end(function(err, res) {
                should.not.exist(err)

                //this line is failing
                assert(this.email.sendOne.calledWith('welcome'));

                done();
            });
    });
});

私が抱えている問題は、assert(this.email.sendOne.calledWith('welcome'))this.email が定義されていないときです。
これは、私が期待していたスコープではないためだと確信しています。これは現在、request.end のスコープになっていると思います。

関数が呼び出されたことをアサートするために、sinon スタブにアクセスするにはどうすればよいですか?

4

1 に答える 1

1

テストを変更thisして、後で使用する値があることがわかっている場所の値を取得し、それを変数に割り当てて内部スコープで使用できるようにし (test以下の例)、次のようにテストを参照します。その変数:

it('sends welcome email', function(done) {
    var test = this;
    request(app)
        .post('/account/register')
        .send(this.accountToPost)
        .expect(200)
        .end(function(err, res) {
            should.not.exist(err)

            assert(test.email.sendOne.calledWith('welcome'));

            done();
        });
});

これを回避するもう 1 つの方法は、mocha テスト オブジェクト自体に値を設定するのではなく、渡されたコールバックdescribeまたは他の適切なクロージャーによって形成されるクロージャーで値を変数にすることです。メインのmocha ページの例では、どれも に何も割り当てられていないことに気付かずにはいられませんthis。そのページの良い例:

describe('Connection', function(){
  var db = new Connection
    , tobi = new User('tobi')
    , loki = new User('loki')
    , jane = new User('jane');

  beforeEach(function(done){
    db.clear(function(err){
      if (err) return done(err);
      db.save([tobi, loki, jane], done);
    });
  })

  describe('#find()', function(){
    it('respond with matching records', function(done){
      db.find({ type: 'User' }, function(err, res){
        if (err) return done(err);
        res.should.have.length(3);
        done();
      })
    })
  })
})

これは、モカの内部と名前が衝突する可能性を避けるために、私が自分で行う方法です。

于 2013-11-30T15:15:12.487 に答える