【问题标题】:Scopes & Closures in Mocha/Chai AssertionsMocha/Chai 断言中的作用域和闭包
【发布时间】: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


    【解决方案1】:

    您可以将变量移动到describe 的范围内。

    describe('CRUD: tests the GET & POST routes', () => {
      let _token;
    
      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);
          _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', _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();
          });
        });
    

    您应该阅读本文以了解 this: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

    【讨论】:

    • 我试过了,但_token 或我使用的任何其他变量也未定义。这对我来说毫无意义,因为它是在 beforeEach 块内访问时定义的。
    • 你确定res.body.token 不是未定义的吗?
    • 是的,它是一个 120 个字符的字符串。
    • 我添加了截图,介意看看吗?可能我的解释不是很清楚。
    猜你喜欢
    • 2018-06-26
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-03-04
    • 2016-08-07
    • 1970-01-01
    • 2021-01-21
    相关资源
    最近更新 更多