【问题标题】:How to make mocha wait before moving to the next test如何在移动到下一个测试之前让摩卡咖啡等待
【发布时间】:2019-06-07 19:03:38
【问题描述】:

当我运行 npm test 时,我得到一个“TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "x-access-token" 错误。似乎 mocha 在获得令牌之前会进行第二次测试。我尝试使用 setTimeOut 方法添加延迟,但仍然出现上述错误。

 // creates valid-user object
    const validUser = {
      username: 'Rigatoni',
      email: 'yahoo.com',
      password: 'qwerty1234567',
    };
    describe('Post Tests', () => {
      // login and get token...
      let token;
      before((done) => {
        request(app)
          .post('/api/v1/auth/login')
          .send(validUser)
          .end((err, res) => {
            // eslint-disable-next-line prefer-destructuring
            token = res.body.token;
            console.log('token', token);
            expect(res.status).to.equal(200);
          });
        // console.log('token test');
        done();
      });

      describe('GET all posts', () => {
        it('should return all posts', (done) => {
          request(app)
            .get('/api/v1/posts')
            .set('x-access-token', token)
            .end((err, res) => {
              expect(res.body.success).to.equal(true);
            });
          done();
        });
      });
    });

【问题讨论】:

    标签: javascript node.js mocha.js supertest


    【解决方案1】:

    您的测试几乎是正确的!

    提供done 回调是为了让 Mocha 知道何时可以继续前进。但是,您在调用异步request 方法之后 在您的测试中调用done(); Mocha 认为测试在你提出请求之前就已经完成了。

    将每个测试的 done() 调用移动到回调函数中(例如,在 expect() 之后的行中),以便在请求完成之前不会执行它。然后 Mocha 会等到测试结束再继续。

    例子:

    request(app)
            .get('/api/v1/posts')
            .set('x-access-token', token)
            .end((err, res) => {
              expect(res.body.success).to.equal(true);
              done();
            });
    

    【讨论】:

      猜你喜欢
      • 2014-10-21
      • 2013-05-24
      • 2015-12-28
      • 2014-07-28
      • 2020-11-11
      • 1970-01-01
      • 2012-07-06
      • 1970-01-01
      • 2019-11-29
      相关资源
      最近更新 更多