【问题标题】:sinon stub nested in describe / request function嵌套在描述/请求函数中的 sinon 存根
【发布时间】:2013-11-30 03:14:53
【问题描述】:

我有一个使用 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 存根来断言该函数已被调用?

【问题讨论】:

    标签: javascript node.js mocha.js sinon supertest


    【解决方案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();
            });
    });
    

    另一种避免这种情况的方法是不在 mocha 测试对象本身上设置值,而是在传递给 describe 的回调或其他适当的闭包形成的闭包中使它们可变。我不禁注意到,在 mocha page 的主要示例中,它们都没有为 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();
          })
        })
      })
    })
    

    这是我自己做的,以避免名称与 mocha 内部发生冲突的可能性。

    【讨论】:

      猜你喜欢
      • 2016-07-11
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多