mardi 18 septembre 2018

Bcrypt.compare not executing in chai/mocha tests, but executing in code

I have some node.js backend in my project. To encrypt passwords I using bcrypt. To compare string password from requst with hashed password in DB I usin bcrypt.compare function. My bcrypt.compare function works well in code. I tested it manually with Postman and it runs well in production. But in tests with chai-http and mocha it hangs up.

Test. I use mocha with chai-http to make http POST request:

describe('Testing login', () => {
  it('should return status 200 when there is such user in DB and password is correct', (done) => {
    chai.request(server)
    .post('/login')
    .send({
      login: 'test@test.test',
      password: 'somepassword'
    })
    .end((err, res) => {
      res.should.have.status(200)
      done()
    })
  })
})

Controller bcrypt fucntion looks like that:

async function auth (req, res) {
  let { login, password } = req.body
  try {
    let payload = {}
    let result = {}
    await
    User.findOne({ where: { userEmail: login } }).then(user => {      
      return result = user
    })
    bcrypt.compare(password, result.dataValues.password, await function (err, data) {
      if (err) {        
        throw Error(err)
      }
      if (result && data) {       
        payload.isAdmin = result.dataValues.isAdmin
        payload.ID = result.dataValues.id
        let token = jwt.sign(payload, 'yoursecret')
        res.status(200).send({ token: token })
      } else { res.status(401) }
    })
  } catch (error) {
    res.sendStatus(500)
  }
}

Is there any way to test this function?

Aucun commentaire:

Enregistrer un commentaire