Getting "Error: the string "Not a valid BCrypt hash." was thrown, throw an Error :)" during Mocha ExpressJS testing

FilmiHero picture FilmiHero · Jun 16, 2015 · Viewed 8k times · Source

I have a MEAN stack app that is using Passport for authentication.

I'm trying to write a unit test that logs in and checks whether you are redirected to the root (/). However, whenever I run Mocha I get the following error message:

1) POST /home Login test should redirect to / after login:
   Error: the string "Not a valid BCrypt hash." was thrown, throw an Error :)

Here's my unit test LoginSpec.js:

var should = require("should");
var app = require("../app");
var mongoose = require("mongoose");
var User = mongoose.model("User");
var request = require("supertest");
var agent = request.agent(app);
...
describe('POST /home', function() {
    before(function(done) {
        user = new User({
            email: "[email protected]",
            firstName: "John",
            lastName: "Doe",
            password: "strongPassword",
            username: "johndoe"
        });

        user.save(done);
    })

    describe('Login test', function() {
        it ('should redirect to / after login', function(done) {
            agent.post('/login')
                .send({
                    username: 'johndoe',
                    password: 'strongPassword'
                })
                .end(function(err, res) {
                    done();
                })
        })

        after(function(done) {
            User.remove().exec();
            return done();
        })
    })
})

Do I need to BCrype my password? If so, how do I do this?

Also, how come some of the online examples I'm seeing for logging in don't do it? Such as NodeJS/Passport - Testing user login with mocha and superagent and How to authenticate Supertest requests with Passport?

Answer

Tiago Gouvêa picture Tiago Gouvêa · Jul 21, 2017

It happen because your password field on database have just a string, not a hashed string.

It must be like $2a$08$LMXAGOARNn4XmnC/rQuhfujrWVwgK/RuHuGpLtXvcv/yruY1v3yXa but probably are just the original password.