I have integrated node.js backend into my project. For encrypting passwords, I am utilizing the bcrypt library. To compare the string password from the request with the hashed password in the database, I am using the bcrypt.compare function. The bcrypt.compare function is functioning properly in my code as it has been manually tested with Postman and works seamlessly in production. However, when conducting tests with chai-http and mocha, it encounters a hang-up.
In my testing process, I utilize mocha with chai-http to initiate an HTTP POST request:
describe('Testing login', () => {
it('should return status 200 when there is a user in the DB with the correct password', (done) => {
chai.request(server)
.post('/login')
.send({
login: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a2b3a5a296a2b3a5a2f8a2b3a5a2">[email protected]</a>',
password: 'somepassword'
})
.end((err, res) => {
res.should.have.status(200)
done()
})
})
})
The controller's bcrypt function is outlined below:
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 a recommended approach for testing this function?
Additional information:
mocha version 5.2.0 - global and local
node v8.11.4
Windows 10 x64
"devDependencies": {
"@types/chai-as-promised": "^7.1.0",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"chai-http": "^4.2.0",
"eslint": "^5.5.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.14.0",
"eslint-plugin-node": "^7.0.1",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"express-unit": "^2.1.1",
"mocha": "^5.2.0",
"mock-express-request": "^0.2.2",
"mock-express-response": "^0.2.2",
"nyc": "^13.0.1",
"proxyquire": "^2.1.0",
"sinon": "^6.2.0",
"supertest": "^3.3.0",
"ws": "3.3.2"
}