sinon stub嵌套在describe / request函数中

时间:2013-11-30 03:14:54

标签: javascript node.js mocha sinon supertest

我使用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')) - 这个电子邮件未定义 我很确定这是因为这不是我期望的范围 - 我认为这现在是request.end的范围?

如何判断我的sinon存根断言该函数被调用?

1 个答案:

答案 0 :(得分:1)

更改您的测试,以便获取this的值,您知道它具有您稍后要使用的值,并将其分配给您可以在内部范围中使用的变量{{1在下面的示例中)然后使用该变量引用您的测试:

test

避免这种情况的另一种方法是不在mocha测试对象本身上设置值,而是在由传递给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 page的示例中,没有任何内容为describe分配任何内容。该页面的一个很好的例子:

this

这就是我自己做的,以避免名字与摩卡的内部冲突的可能性。

相关问题