【发布时间】:2016-05-08 00:59:56
【问题描述】:
我正在为一个快速应用程序编写一些测试,我想知道如何从另一个断言块中正确访问一个变量。我试图访问的变量是this.token = res.body.token
每当我尝试访问它时,它都会出现未定义(除了在 beforeEach 块中访问它时)。我怎样才能访问这个变量?我需要使用令牌在我的测试中为我的 POST 请求设置标头。
代码:
describe('CRUD: tests the GET & POST routes', () => {
beforeEach(done => {
chai.request('localhost:3000')
.post('/app/signup')
.send({ email: 'meow@test.com', password: 'testpass' })
.end((err, res) => {
if (err) return console.log(err);
this.token = res.body.token; // this variable holds a token when accessed within this scope (tested it with node debugger)
done();
});
});
it('should create with a new cat with a POST request', (done) => {
chai.request('localhost:3000')
.post('/app/cats')
.set('token', this.token) // when accessed here, it is undefined...
.send({ username: 'cat_user' })
.end((err, res) => {
expect(err).to.eql(null);
expect(res).to.have.status(200);
expect(res.body.name).to.eql('test cat');
expect(res.body).to.have.property('_id');
done();
});
});
编辑:这是我的终端在节点调试模式下的屏幕截图。如您所见,当它遇到第一个调试器中断并访问_token 时,它包含令牌。然而,在下一个调试器中断时,它出现空......(也许这意味着调试器中的其他东西?)
【问题讨论】:
标签: node.js scope mocha.js chai