Skip to content

Commit

Permalink
Ft: auth (new user needs to verify one's account before login)
Browse files Browse the repository at this point in the history
mocked all email service calling during the test
  • Loading branch information
teerenzo authored and MugemaneBertin2001 committed May 29, 2024
2 parents 9b8d8e4 + be845b7 commit ee0c6fe
Show file tree
Hide file tree
Showing 16 changed files with 406 additions and 24 deletions.
8 changes: 8 additions & 0 deletions __test__/cart.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import { dummy } from "./prod";
import * as userServices from "../src/services/user.service"
import { number } from "joi";

jest.mock("../src/services/mail.service", () => ({
sendEmailService: jest.fn(),
sendNotification: jest.fn(),
}));

const queryInterface = sequelize.getQueryInterface();

let sellerToken: any;
Expand All @@ -28,19 +33,22 @@ describe("testing cart", () => {
name: "admin123",
username: "admin123",
email: "[email protected]",
isVerified:true,
password: await bcrypt.hash("password", 10),
roleId: 3,
};

const testBuyer = {
name: "buyer123",
username: "buyer123",
isVerified:true,
email: "[email protected]",
password: await bcrypt.hash("password", 10),
};
const testSeller = {
name: "seller123",
username: "seller123",
isVerified:true,
email: "[email protected]",
password: await bcrypt.hash("password", 10),
};
Expand Down
9 changes: 9 additions & 0 deletions __test__/payment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ let adminToken: any;
let sellerToken: any;


jest.mock("../src/services/mail.service", () => ({
sendEmailService: jest.fn(),
sendNotification: jest.fn(),
}));


describe("test stripe api payment", () => {
beforeAll(async () => {
try {
Expand All @@ -23,6 +29,7 @@ describe("test stripe api payment", () => {
const testAdmin = {
name: "admin123",
username: "admin123",
isVerified:true,
email: "[email protected]",
password: await bcrypt.hash("password", 10),
roleId: 3,
Expand All @@ -31,13 +38,15 @@ describe("test stripe api payment", () => {
const testBuyer = {
name: "buyer123",
username: "buyer123",
isVerified:true,
email: "[email protected]",
password: await bcrypt.hash("password", 10),
};

const testSeller = {
name: "seller123",
username: "seller123",
isVerified:true,
email: "[email protected]",
password: await bcrypt.hash("password", 10),
};
Expand Down
41 changes: 33 additions & 8 deletions __test__/product.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,21 @@ import User from "../src/sequelize/models/users";
import bcrypt from "bcryptjs";
import { Role } from "../src/sequelize/models/roles";
import redisClient from "../src/config/redis";
import { response } from "express";
import { placeOrder } from "../src/services/payment.service";
import Cart from "../src/sequelize/models/Cart";
import CartItem from "../src/sequelize/models/CartItem";
import OrderItem from "../src/sequelize/models/orderItems";
import * as userService from "../src/services/user.service"
import { generateVerificationToken } from "../src/utils/generateResetToken";

jest.mock("../src/services/mail.service", () => ({
sendEmailService: jest.fn(),
sendNotification: jest.fn(),
}));

const userData: any = {
name: "yvanna",
username: "testuser",
isVerified:true,
email: "[email protected]",
role:"seller",
password: "test1234",
Expand All @@ -28,6 +33,7 @@ const userData: any = {
const dummySeller = {
name: "dummy1234",
username: "username1234",
isVerified:true,
email: "[email protected]",
password: "1234567890",
};
Expand All @@ -36,6 +42,7 @@ const product:any = {
name: "pens",
images: ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"],
stockQuantity: 8,

price: 5000,
discount: 3.5,
categoryID: 1,
Expand All @@ -44,6 +51,7 @@ const product:any = {
const dummyBuyer = {
name: "test user",
username: "testUser",
isVerified:true,
email: "[email protected]",
password: "soleil00",
}
Expand All @@ -61,6 +69,7 @@ describe("Testing product Routes", () => {
await connect();
const testAdmin = {
name: "admin123",
isVerified:true,
username: "admin123",
email: "[email protected]",
password: await bcrypt.hash("password", 10),
Expand All @@ -77,8 +86,8 @@ describe("Testing product Routes", () => {
])

await User.create(testAdmin);

const dummy = await request(app).post("/api/v1/users/register").send(dummySeller);
await User.create(dummySeller);
// await request(app).post("/api/v1/users/register").send(dummySeller);
await Product.destroy({});
await Category.destroy({truncate:true});
} catch (error) {
Expand Down Expand Up @@ -106,6 +115,13 @@ describe("Testing product Routes", () => {
expect(response.status).toBe(201);
})
let buyerToken: any;
it("It should verify user account.",async()=>{
const token = generateVerificationToken('[email protected]', 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)

test("should login an buyer", async () =>{
const response = await request(app).post("/api/v1/users/login").send({
Expand All @@ -122,21 +138,29 @@ describe("Testing product Routes", () => {
.send(product)
expect(response.status).toBe(401);
},2000);

test("should login an Admin", async () =>{
const response = await request(app).post("/api/v1/users/login").send({
email: "[email protected]",
password: "password"
password: "password"
})
adminToken = response.body.token;
expect(response.status).toBe(200)
});
it("It should verify user account.",async()=>{
const token = generateVerificationToken(dummySeller.email, 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)

test("should update dummyseller's role to seller", async () => {
const logDummySeller = await request(app).post("/api/v1/users/login").send({
email: dummySeller.email,
password: dummySeller.password,
});
expect(logDummySeller.status).toBe(200);
// expect(logDummySeller.status).toBe(200);
expect(logDummySeller.body.message).toBe('Logged in')
token = logDummySeller.body.token;

const seller = await userService.getUserByEmail(dummySeller.email)
Expand All @@ -149,6 +173,7 @@ describe("Testing product Routes", () => {
})
.set("Authorization", "Bearer " + adminToken);
expect(response.status).toBe(200);
expect(response.body.message).toBe('User role updated successfully');

});

Expand Down Expand Up @@ -477,7 +502,7 @@ test('It should return status 200 for removed category',async() =>{
})
it("changing product availability of product which does not exist", async ()=>{
const response = await request(app)
.patch(`/api/v1/products/${91}/status`)
.patch(`/api/v1/products/${4444444}/status`)
.set("Authorization", "Bearer " + token);
expect(response.body.message).toBe('Product not found')
})
Expand Down
73 changes: 66 additions & 7 deletions __test__/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,14 @@ import { QueryTypes } from "sequelize";
// import redisClient from "../src/config/redis";
import Redis from "ioredis";
import { env } from "../src/utils/env";
import { generateResetToken } from "../src/utils/generateResetToken";
import { generateResetToken, generateVerificationToken } from "../src/utils/generateResetToken";

let redisClient:any;
let redisClient: any;

jest.mock("../src/services/mail.service", () => ({
sendEmailService: jest.fn(),
sendNotification: jest.fn(),
}));


const userData: any = {
Expand All @@ -32,12 +37,13 @@ const userData: any = {
const dummySeller = {
name: "dummy1234",
username: "username1234",
email: "soleilcyber00@gmail.com",
email: "srukundo01@gmail.com",
password: "1234567890",
lastPasswordUpdateTime: "3000, 11, 18"
};
const userTestData = {
newPassword: "Test@123",
isVerified:true,
confirmPassword: "Test@123",
wrongPassword: "Test456",
};
Expand Down Expand Up @@ -109,6 +115,14 @@ describe("Testing user Routes", () => {
expect(response.status).toBe(201);
}, 20000);

it("It should verify user account.",async()=>{
const token = generateVerificationToken(userData.email, 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)


test("should return 409 when registering with an existing email", async () => {
User.create(userData);
Expand Down Expand Up @@ -138,6 +152,7 @@ describe("Testing user Routes", () => {
password: userData.password,
});
expect(response.status).toBe(200);
expect(response.body.message).toBe("Logged in");
token = response.body.token;
});

Expand Down Expand Up @@ -204,21 +219,36 @@ describe("Testing user Routes", () => {
expect(response.body.status).toBe(401);
spyonOne.mockRestore();
}, 20000);
it("It should verify user account.",async()=>{
const token = generateVerificationToken('[email protected]', 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)

test("should login an Admin", async () =>{
const response = await request(app).post("/api/v1/users/login").send({
email: "[email protected]",
password: "password"
password: "password"
})
adminToken = response.body.token;
});
it("It should verify user account.",async()=>{
const token = generateVerificationToken(dummySeller.email, 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)

test("should update dummyseller's role to seller", async () => {
const logDummySeller = await request(app).post("/api/v1/users/login").send({
email: dummySeller.email,
password: dummySeller.password,
});
expect(logDummySeller.status).toBe(200);
expect(logDummySeller.body.message).toBe("Logged in");
const seller = await userServices.getUserByEmail(dummySeller.email);
const dummySellerId = seller?.id;

Expand All @@ -230,18 +260,25 @@ describe("Testing user Routes", () => {
.set("Authorization", "Bearer " + adminToken);

expect(response.status).toBe(200);
// expect(response.body.message).toBe('User role updated successfully');

});

test("Should send otp verification code", async () => {
test("Should send otp verification code", async () => {
jest.unmock("../src/services/mail.service");
const originalMailService = jest.requireActual("../src/services/mail.service");
const spy = jest.spyOn(mailServices, "sendEmailService");
const response = await request(app).post("/api/v1/users/login").send({
email: dummySeller.email,
password: dummySeller.password,
});

expect(response.body.message).toBe("OTP verification code has been sent ,please use it to verify that it was you");
// expect(spy).toHaveBeenCalled();
expect(response.body.message).toBe("OTP verification code has been sent ,please use it to verify that it was you");
expect(spy).toHaveBeenCalled()
jest.mock("../src/services/mail.service", () => ({
sendEmailService: jest.fn(),
sendNotification: jest.fn(),
}));
}, 70000);

test("should log a user in to retrieve a token", async () => {
Expand Down Expand Up @@ -552,6 +589,28 @@ describe('Patch /api/v1/users/reset-password', () => {
},60000);
});

describe("Verifying user account",()=>{
it("It should verify user account.",async()=>{
await User.create(userData)
const token = generateVerificationToken(userData.email, 60);
const response = await request(app)
.get(`/api/v1/users/verify-user?token=${token}`)
expect(response.status).toBe(200)
expect(response.body.message).toBe('User verified successfully.')
},60000)

it("It should send a verification link.",async()=>{
const response = await request(app)
.post('/api/v1/users/verify-user-email')
.send({
email:userData.email
})
expect(response.status).toBe(409)
expect(response.body.message).toBe("User is already verified.")
},60000)

})

afterAll(async () => {
try {
await sequelize.query('TRUNCATE TABLE profiles, users CASCADE');
Expand Down
Loading

0 comments on commit ee0c6fe

Please sign in to comment.