Mocha变量已初始化,但使用时为null

时间:2019-07-17 16:21:06

标签: node.js mocha

我正在尝试测试受auth保护的路由。我在before()挂钩中获得了令牌,并在控制台中将其打印出来-很好,令牌存在于响应中。我将其分配给变量,但是当我在下一个文本案例中发送该变量时,它为null。

class B{
    public:
    virtual void f2(A a){cout<<"B::f2()"<<endl;}
};

class C:public B{
private:
    public:
    virtual void f2(A& a){cout<<"C::f2(A&)"<<endl;
    }

};

class D:public C{
    public:
    void f2(A a){cout<<"D::f2(A)"<<endl;}
};

int main(void)
{
    B* b = new D();
    A a2 = A();
    A &a = a2;
    b->f2(a); // prints D::f2 - should'nt it print B::f2??

    C* c = new D();
    c->f2(a); // prints C::f2 - as expected
    return 0;

}

1 个答案:

答案 0 :(得分:0)

在进行了一些反复试验后,我知道了。问题是在我在下面的测试中使用之前,在before()函数中进行的调用未完成。因此,基本上token仍然为空。这是固定代码:

    const assert = require('assert'),
    request = require('supertest'),
    app = require('../app'),
    superagent = require('superagent')

    describe('Testing the api/product POST route', function() {

    let token = null;
    const credentials = {
        email: 'test@test.com',
        password: 'test'
    }

    before(async function() {
        const res = await superagent
            .post('http://localhost:3000/api/users/login')
            .send(credentials) // sends a JSON post body
            .set('Content-Type', 'application/json')
            token = res.body.token
    }),

    it('should return 422 status when you send an empty product object', function() {
        request(app)
            .post('/api/products')
            .send({})
            .set('Content-Type', 'application/json')
            .set('Authorization', 'Bearer ' + token)
            .then((res) => {
                assert.equal(1, 1)
            })
    })
})