Skip to content

Commit

Permalink
feat(user-Test): implementing sign up using jest
Browse files Browse the repository at this point in the history
  • Loading branch information
Tuyisenge2 committed Apr 22, 2024
1 parent cef80c8 commit 5cec93e
Show file tree
Hide file tree
Showing 9 changed files with 278 additions and 223 deletions.
35 changes: 31 additions & 4 deletions src/__test__/users.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ import {
login_user,
login_user_invalid_email,
login_user_wrong_credentials,
register_user,
NewUser,
user_bad_request,
User_without_email,
exist_user,
} from "../mock/static";


import { createUser } from "../services/user.services";
jest.setTimeout(30000);

function logErrors(
Expand All @@ -27,17 +32,34 @@ const Jest_request = request(app.use(logErrors));
describe("USER API TEST", () => {
beforeAll(async () => {
await connectionToDatabase();
await createUser(exist_user);
});

afterAll(async () => {
await deleteTableData(User, "users");
});

it("should create a new user", async () => {
// Your test implementation goes here
it("it should return a user not found and status 400", async () => {
const { body } = await Jest_request.post("/api/v1/users/register")
.send(register_user)
.send(user_bad_request)
.expect(400);
});

it("it should return a user exist and status 409 when Email is already used in database", async () => {
const { body } = await Jest_request.post("/api/v1/users/register")
.send(exist_user)
.expect(409);
expect(body.status).toStrictEqual("CONFLICT");
expect(body.message).toStrictEqual("User already exist!");
});
});
it("it should register a user and return 201", async () => {
const { body } = await Jest_request.post("/api/v1/users/register")
.send(NewUser)
.expect(201);
expect(body.status).toStrictEqual("SUCCESS");
expect(body.message).toStrictEqual("Account Created successfully!");
expect(body.token).toBeDefined();
});

/**
Expand Down Expand Up @@ -78,4 +100,9 @@ describe("USER API TEST", () => {
expect(body.status).toStrictEqual("BAD REQUEST");
expect(body.message).toBeDefined();
})
/**
* ----------------------------register new user --------------------------------------------
*/
describe("FAILED SIGN UP", () => {

});
64 changes: 29 additions & 35 deletions src/controllers/userController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,42 @@ import { NextFunction, Request, Response } from "express";
import { UserModelAttributes } from "../database/models/User";
import { generateAccessToken } from "../helpers/security.helpers";
import { HttpException } from "../utils/http.exception";
import passport from "../middlewares/passport";
import passport, { CustomVerifyOptions } from "../middlewares/passport";

interface InfoAttribute {
message: string;
}

interface InfoAttribute extends CustomVerifyOptions {}

const registerUser = async (
req: Request,
res: Response,
next: NextFunction,
) => {
try {
if (req.body) {
passport.authenticate(
"signup",
(err: Error, user: UserModelAttributes, info: InfoAttribute) => {
if (!user) {
return res
.status(404)
.json(new HttpException("NOT FOUND", info.message));
}
(req as any).login(user, async () => {
if (err) {
return res
.status(400)
.json(new HttpException("BAD REQUEST", "Bad Request!"));
}
const token = generateAccessToken({ id: user.id, role: user.role });
const response = new HttpException(
"SUCCESS",
"Account Created successfully!",
).response();
res.status(201).json({ ...response, token });
});
},
)(req, res, next);
}
} catch (error) {
res
.status(500)
.json(new HttpException("SERVER ERROR", "Something went wrong!"));
}
try {
if (req.body) {
passport.authenticate(
"signup",
(err: Error, user: UserModelAttributes, info: InfoAttribute) => {
if (!user) {
return res
.status(info.statusNumber || 400)
.json(new HttpException(info.status, info.message));
}
req.login(user, async () => {
const token = generateAccessToken({ id: user.id, role: user.role });
const response = new HttpException(
"SUCCESS",
"Account Created successfully!"
).response();
res.status(201).json({ ...response, token });
});
}
)(req, res, next);
}
} catch (error) {
res
.status(500)
.json(new HttpException("SERVER FAIL", "Something went wrong!"));
}
};

const login = async (req: Request, res: Response, next: NextFunction) => {
Expand Down
File renamed without changes.
175 changes: 93 additions & 82 deletions src/middlewares/passport.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,93 @@
import { Request } from "express";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { User } from "../database/models/User";
import { isValidPassword } from "../utils/password.checks";
import { hashPassword } from "../utils/password";

passport.serializeUser(function (user: any, done) {
done(null, user);
});

passport.deserializeUser(function (user: any, done) {
done(null, user);
});

passport.use(
"signup",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
async (req, email, password, done) => {
try {
const data = {
email: email.trim(),
password: await hashPassword(password),
confirmPassword: await hashPassword(req.body.confirmPassword),
userName:
req.body.userName == null
? req.body.email.split("@")[0]
: req.body.userName,
firstName: req.body.firstName,
lastName: req.body.lastName,
role: "BUYER",
};
const user = await User.create({ ...data });
if (!user) {
return done(null, false, {
message: "Something went wrong",
});
}
done(null, user);
} catch (error) {
done(error);
}
},
),
);

passport.use(
"login",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
async (_req: Request, email, password, done) => {
try {
const user = await User.findOne({ where: { email } });

if (!user) return done(null, false, { message: "Wrong credentials!" });

const currPassword = user.dataValues.password;

const isValidPass = await isValidPassword(password, currPassword);

if (!isValidPass) {
return done(null, false, { message: "Wrong credentials!" });
}

return done(null, user);
} catch (error) {
done(error);
}
},
),
);

export default passport;
import { Request } from "express";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { User } from "../database/models/User";
import { isValidPassword } from "../utils/password.checks";
import { hashPassword } from "../utils/password";
export interface CustomVerifyOptions {
message: string;
status: string;
statusNumber?: number;
}
passport.serializeUser(function (user: any, done) {
done(null, user);
});

passport.deserializeUser(function (user: any, done) {
done(null, user);
});

passport.use(
"signup",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
async (req, email, password, done) => {
try {
const data = {
email: email.trim(),
password: await hashPassword(password),
confirmPassword: await hashPassword(req.body.confirmPassword),
userName:
req.body.userName == null
? req.body.email.split("@")[0]
: req.body.userName,
firstName: req.body.firstName,
lastName: req.body.lastName,
role: "BUYER",
};
const userEXist = await User.findOne({
where: {
email: data.email,
},
});
if (userEXist) {
const options: CustomVerifyOptions = {
statusNumber: 409,
message: "User already exist!",
status: "CONFLICT",
};
return done(null, false, options);
}
const user = await User.create({ ...data });
done(null, user);
} catch (error) {
done(error);
}
}
)
);

passport.use(
"login",
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
passReqToCallback: true,
},
async (_req: Request, email, password, done) => {
try {
const user = await User.findOne({ where: { email } });

if (!user) return done(null, false, { message: "Wrong credentials!" });

const currPassword = user.dataValues.password;

const isValidPass = await isValidPassword(password, currPassword);

if (!isValidPass)
return done(null, false, { message: "Wrong credentials!" });

return done(null, user);
} catch (error) {
done(error);
}
}
)
);

export default passport;
Loading

0 comments on commit 5cec93e

Please sign in to comment.