lundi 13 juillet 2020

JWT Malformed error when testing express app using mocha

I am trying to write test files for my user routes. One thing I am having an issue with is the delete route for a user. The route is defined as follows /api/users and makes a delete request. This route is protected and everything works fine on postman. The header that I set in Postman is Authorization.

Everything looks fine but in my test file the result is a bit weird. Here is my code

describe('Users', () => {
  beforeEach((done) => {
    User.deleteMany({}, (err) => {
      done();
    });
  });    
describe('/DELETE user', () => {
    it('it should delete a user with authorized token', (done) => {
      const user = new User({
        username: 'testuser1',
        email: 'testuser1@gmail.com',
        password: 'password',
        passwordConfirm: 'password',
      });

      let token = null;

      chai
        .request(server)
        .post(`/api/users/signup`)
        .send(user)
        .end((err, res) => {
          token = res.body.token;
        });

      chai
        .request(server)
        .delete(`/api/users`)
        .set('Authorization', 'Bearer ' + token)
        .end((err, res) => {
          res.should.have.status(201);
          res.body.should.be.a('object');
          res.body.should.have.property('status').eql('success');
          res.body.should.have
            .property('message')
            .eql('User deleted successfully!');
        });
      done();
    });
  });
});

The test passes but I get this JWT malformed error and I'm not sure why. I know that I am using Bearer in front of the actual token

This is what the error mentions

(node:3059) UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed (node:3059) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2) (node:3059) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I really don't understand what is going on because if it works fine when I test it in postman and all I am doing here is adding the token using .set('Authorization', 'Bearer ' + token) in my mind it should work the same.

Aucun commentaire:

Enregistrer un commentaire