jeudi 1 février 2018

API Route Testing Unexpected Results

I am writing a MEAN API at the minute and I have a route called /authenticate where users can log in. Below I have shown the route it's self.

 // User Login Route - http://localhost:8080/api/authenticate
router.post('/authenticate', function(req, res) {
   User.findOne({ username: req.body.username }).select('email username password').exec(function(err, user) {
      if (err) throw err;

      if (!user) {
          res.json({ success: false, message: 'Could not authenticate user.'});
      } else if (user) {
            //Using comparePassword Method
          if (req.body.password) {
              var validatePassword = user.comparePassword(req.body.password);
              if (!validatePassword) {
                  res.json({success : false, message : 'Could not authenticate password!'});
              }
              else{
                  res.status(200).json({success : true, message : 'User authenticated!'});
              }
          }
          else{
              res.json({success : false, message : 'Not password provided!'});
          }
      }
   });
});

I am now trying to test the route using the mocha and chai libraries. Below I have shown the describe block that I am using to test this function.

describe('POST /authenticate', function() {
   it('should return an error', function (done) {
      var newUser = {
          "username" : "testetet",
          "password" : "hgfhghg"
      };
      chai.request(server)
          .post('/api/authenticate')
          .send(newUser)
          .end(function (err, res) {
              expect(res).to.have.status(201);
              expect(res.body).to.have.property('message').equal('User Created.');
          });
      done();
   });
});

As you can see from the test above the test should fail because none of the response criteria in the test matches the response that should be coming back from the API, but it still continues to pass every time I run it.

Does anyone have any ideas why this would be happening? Thanks for any help in advance.

Aucun commentaire:

Enregistrer un commentaire