Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#-187431151 implementing jest test in sign up #15

Merged
merged 2 commits into from
Apr 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ jobs:
curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
chmod +x ./cc-test-reporter
./cc-test-reporter before-build

- name: Run tests
run: npm run test

Expand Down
29 changes: 24 additions & 5 deletions src/__test__/users.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import {
login_user,
login_user_invalid_email,
login_user_wrong_credentials,
register_user,
NewUser,
user_bad_request
} from "../mock/static";


jest.setTimeout(30000);

function logErrors(
Expand All @@ -32,13 +34,28 @@ describe("USER API TEST", () => {
afterAll(async () => {
await deleteTableData(User, "users");
});

it("should create a new user", async () => {
// Your test implementation goes here
it("it should register a user and return 201", async () => {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similar blocks of code found in 2 locations. Consider refactoring.

const { body } = await Jest_request.post("/api/v1/users/register")
.send(register_user)
.send(NewUser)
.expect(201);
expect(body.status).toStrictEqual("SUCCESS");
expect(body.message).toStrictEqual("Account Created successfully!");
expect(body.token).toBeDefined();
});
it("it should return a user not found and status 400", async () => {
const { body } = await Jest_request.post("/api/v1/users/register")
.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(NewUser)
.expect(409);
expect(body.status).toStrictEqual("CONFLICT");
expect(body.message).toStrictEqual("User already exist!");
});


/**
* ---------------------------- LOGIN --------------------------------------------
Expand Down Expand Up @@ -78,4 +95,6 @@ describe("USER API TEST", () => {
expect(body.status).toStrictEqual("BAD REQUEST");
expect(body.message).toBeDefined();
})


});
66 changes: 30 additions & 36 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 FAILS", "Something went wrong!"));
}
};

const login = async (req: Request, res: Response, next: NextFunction) => {
Expand Down Expand Up @@ -82,6 +76,6 @@ const login = async (req: Request, res: Response, next: NextFunction) => {
};

export default {
login,
registerUser,
login
};
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";
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Parsing error: 'import' and 'export' may appear only with 'sourceType: module'

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