Search code examples
javascriptnode.jsmocha.jssupertest

How to make mocha wait before moving to the next test


When i ran npm test i got a 'TypeError [ERR_HTTP_INVALID_HEADER_VALUE]: Invalid value "undefined" for header "x-access-token"' error. Seems like mocha moves on to the second test before getting the token. I tried adding a delay with the setTimeOut method but i still got the above error.

 // 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();
        });
      });
    });

Solution

  • Your tests are almost right!

    The done callback is provided to let Mocha know when it's OK to move on. However, you are calling done() in your tests right after calling the asynchronous request method; Mocha thinks the test is done before you even make the request.

    Move your done() call for each test into a callback function (for example, on the line right after your expect()), so that it isn't executed until after the request completes. Then Mocha will wait until the test is over before moving on.

    Example:

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