Skip to content

Commit

Permalink
fix e2e tests
Browse files Browse the repository at this point in the history
  • Loading branch information
daisykucharski committed Oct 15, 2023
1 parent 5c390c0 commit c39223e
Show file tree
Hide file tree
Showing 11 changed files with 118 additions and 47 deletions.
2 changes: 1 addition & 1 deletion packages/api-v2/ormconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const ormconfig: TypeOrmModuleOptions = {
username: process.env.POSTGRES_USERNAME,
password: process.env.POSTGRES_PASSWORD || "",
database: process.env.POSTGRES_DATABASE,
synchronize: false,
synchronize: process.env.NODE_ENV === "testing",
entities: [Student, Plan],
migrations: ["./dist/migrations/*.js"],
cli: {
Expand Down
2 changes: 1 addition & 1 deletion packages/api-v2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:db:up": "docker-compose -f ../../infrastructure/test/docker-compose.e2e.yml up -d",
"test:db:down": "docker-compose -f ../../infrastructure/test/docker-compose.e2e.yml down",
"test:e2e": "yarn g:cross-env NODE_ENV=testing jest --config ./test/jest-e2e.json --detectOpenHandles",
"test:e2e": "yarn g:cross-env NODE_ENV=testing jest --config ./test/jest-e2e.json --detectOpenHandles --no-cache --force-exit",
"typeorm": "yarn g:cross-env NODE_ENV=development ts-node --project ./tsconfig.json ../../node_modules/typeorm/cli.js",
"dev:db:reset": "yarn typeorm schema:drop",
"dev:migration:generate": "yarn dev:db:reset && yarn typeorm migration:run && yarn typeorm migration:generate",
Expand Down
8 changes: 5 additions & 3 deletions packages/api-v2/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,11 @@ export class AuthController {
sameSite: "strict",
secure: isSecure,
});
await this.emailConfirmationService.sendVerificationLink(
createStudentDto.email
);
if (process.env.NODE_ENV !== "testing") {
await this.emailConfirmationService.sendVerificationLink(
createStudentDto.email
);
}
return student;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/api-v2/src/major/major.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export class MajorService {
{ mesage: "Major year not found", catalogYear },
MajorService.formatMajorServiceCtx("findByMajorAndYear")
);
console.log("major year not found");
return null;
}

Expand All @@ -27,6 +28,7 @@ export class MajorService {
{ mesage: "Major within year not found", majorName, catalogYear },
MajorService.formatMajorServiceCtx("findByMajorAndYear")
);
console.log("major within year not found");
return null;
}

Expand Down
55 changes: 37 additions & 18 deletions packages/api-v2/src/student/student.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ import {
UpdateStudentDto,
} from "@graduate/common";
import { Student } from "./entities/student.entity";
import { EmailAlreadyExists, NewPasswordsDontMatch, WeakPassword, WrongPassword } from "./student.errors";
import {
EmailAlreadyExists,
NewPasswordsDontMatch,
WeakPassword,
WrongPassword,
} from "./student.errors";

@Injectable()
export class StudentService {
Expand All @@ -25,7 +30,7 @@ export class StudentService {
constructor(
@InjectRepository(Student)
private studentRepository: Repository<Student>
) { }
) {}

async create(
createStudentDto: SignUpStudentDto
Expand Down Expand Up @@ -161,49 +166,63 @@ export class StudentService {
return formatServiceCtx(StudentService.name, methodName);
}

async changePassword(uuid: any, changePasswordDto: ChangePasswordDto): Promise<void | WeakPassword | WrongPassword> {
const { currentPassword, newPassword, newPasswordConfirm } = changePasswordDto;
async changePassword(
uuid: any,
changePasswordDto: ChangePasswordDto
): Promise<void | WeakPassword | WrongPassword> {
const { currentPassword, newPassword, newPasswordConfirm } =
changePasswordDto;
const student = await this.findByUuid(uuid);

if (newPassword !== newPasswordConfirm) {
return new NewPasswordsDontMatch();
}

const { password: trueHashedPassword } = student;
const isValidPassword = await bcrypt.compare(currentPassword, trueHashedPassword);
const isValidPassword = await bcrypt.compare(
currentPassword,
trueHashedPassword
);

if (!isValidPassword) {
this.logger.debug(
{ message: "Invalid password", oldPassword: currentPassword },
);
this.logger.debug({
message: "Invalid password",
oldPassword: currentPassword,
});
return new WrongPassword();
}

if (!isStrongPassword(newPassword)) {
this.logger.debug(
{ message: "weak password", oldPassword: currentPassword },
);
this.logger.debug({
message: "weak password",
oldPassword: currentPassword,
});
return new WeakPassword();
}
await this.studentRepository.save(Object.assign(student, { password: newPassword }));
await this.studentRepository.save(
Object.assign(student, { password: newPassword })
);
}

async resetPassword(email, resetPasswordData: ResetPasswordDto): Promise<Student | Error> {
async resetPassword(
email,
resetPasswordData: ResetPasswordDto
): Promise<Student | Error> {
const { password, passwordConfirm } = resetPasswordData;

const student = await this.findByEmail(email)
const student = await this.findByEmail(email);

if (password !== passwordConfirm) {
return new NewPasswordsDontMatch();
}

if (!isStrongPassword(password)) {
this.logger.debug(
{ message: "weak password", password },
);
this.logger.debug({ message: "weak password", password });
return new WeakPassword();
}

return await this.studentRepository.save(Object.assign(student, { password }))
return await this.studentRepository.save(
Object.assign(student, { password })
);
}
}
18 changes: 16 additions & 2 deletions packages/api-v2/test/auth/auth.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ import { Connection } from "typeorm";
import { dropStudentTable, initializeApp } from "../../test/utils";
import { testUser1 } from "../../test/testingData";

jest.useRealTimers();
jest.setTimeout(10000);

describe("AuthController (e2e)", () => {
let app: INestApplication;
let connection: Connection;

beforeEach(async () => {
beforeAll(async () => {
app = await initializeApp();
connection = app.get(Connection);

Expand All @@ -30,7 +33,8 @@ describe("AuthController (e2e)", () => {
.post("/auth/register")
.send({
email: "[email protected]",
password: "1234567890",
password: "1234567890a",
passwordConfirm: "1234567890a",
})
.expect(201);

Expand All @@ -50,13 +54,23 @@ describe("AuthController (e2e)", () => {
.into(Student)
.values([{ ...testUser1 }]);

await request(app.getHttpServer())
.post("/auth/register")
.send(testUser1)
.expect(201);

await request(app.getHttpServer())
.post("/auth/register")
.send(testUser1)
.expect(400);
});

it("logs in with valid credentials", async () => {
await request(app.getHttpServer())
.post("/auth/register")
.send(testUser1)
.expect(201);

const res = await request(app.getHttpServer())
.post("/auth/login")
.send(testUser1)
Expand Down
3 changes: 3 additions & 0 deletions packages/api-v2/test/jest-e2e.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleNameMapper": {
"^src/(.*)": "<rootDir>/../src/$1"
},
"transformIgnorePatterns": ["^.+\\.js$"]
}
13 changes: 8 additions & 5 deletions packages/api-v2/test/major/major.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { INestApplication } from "@nestjs/common";
import * as request from "supertest";
import { initializeApp } from "../../test/utils";

jest.useRealTimers();
jest.setTimeout(10000);

describe("MajorController (e2e)", () => {
let app: INestApplication;

Expand All @@ -15,7 +18,7 @@ describe("MajorController (e2e)", () => {

it("retrieves the major for a valid year and major name", async () => {
const response = await request(app.getHttpServer())
.post("/majors/2022/Computer%20Science,%20BSCS")
.get("/majors/2022/Computer%20Science,%20BSCS")
.expect(200);

const major = response.body;
Expand All @@ -25,14 +28,14 @@ describe("MajorController (e2e)", () => {
it("fails to retrieve a major from an invalid year", () => {
const INVALID_YEAR = 2000;
return request(app.getHttpServer())
.post(`/majors/${INVALID_YEAR}/Computer%20Science,%20BSCS`)
.expect(400);
.get(`/majors/${INVALID_YEAR}/Computer%20Science,%20BSCS`)
.expect(404);
});

it("fails to retrieve a major from a valid year but invalid major name", () => {
const INVALID_MAJOR_NAME = "wrong";
return request(app.getHttpServer())
.post(`/majors/2022/${INVALID_MAJOR_NAME}`)
.expect(400);
.get(`/majors/2022/${INVALID_MAJOR_NAME}`)
.expect(404);
});
});
31 changes: 22 additions & 9 deletions packages/api-v2/test/plan/plan.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,15 @@ import { Plan } from "../../src/plan/entities/plan.entity";
import * as request from "supertest";
import { Connection } from "typeorm";
import { dropStudentTable, initializeApp } from "../../test/utils";
import { testPlan, testUser1, testUser2 } from "../../test/testingData";
import {
testPlan,
testUser1,
testUser2,
testUser3,
} from "../../test/testingData";

jest.useRealTimers();
jest.setTimeout(10000);

describe("PlanController (e2e)", () => {
let app: INestApplication;
Expand All @@ -12,18 +20,19 @@ describe("PlanController (e2e)", () => {
let uuid: string;
let planID: number;

beforeEach(async () => {
beforeAll(async () => {
app = await initializeApp();
});

beforeAll(async () => {
connection = app.get(Connection);

// create student
const res = await request(app.getHttpServer())
.post("/auth/register")
.send(testUser1);

// save accessToken and user ID
cookie = res.header["set-cookie"];
cookie = res.headers["set-cookie"];
uuid = res.body.uuid;

// insert plan into db
Expand All @@ -39,18 +48,22 @@ describe("PlanController (e2e)", () => {
.createQueryBuilder()
.select("plan")
.from(Plan, "plan")
.where("plan.name = :name", { name: "Test Plan" })
.where("plan.name = :name AND plan.student.uuid = :uuid", {
name: "Test Plan",
uuid,
})
.getOne();

planID = plan.id;
});

afterEach(async () => {
afterAll(async () => {
await dropStudentTable(connection);
});

afterAll(async () => {
await app.close();
await connection.close();
});

it("creates a plan for a signed in user", async () => {
Expand Down Expand Up @@ -96,7 +109,7 @@ describe("PlanController (e2e)", () => {
await request(app.getHttpServer())
.patch(`/plans/${planID}`)
.set("Cookie", cookie)
.send({ catalogYear: 2018 })
.send({ name: "robert is stinky" })
.expect(200);
});

Expand All @@ -117,7 +130,7 @@ describe("PlanController (e2e)", () => {
await request(app.getHttpServer())
.patch(`/plans/${planID}`)
.set("Cookie", badCookie)
.send({ catalogYear: 2018 })
.send({ catalogYear: 2021 })
.expect(403);
});

Expand All @@ -135,7 +148,7 @@ describe("PlanController (e2e)", () => {
it("fails to delete a plan that does not belong to a user", async () => {
const res = await request(app.getHttpServer())
.post("/auth/register")
.send(testUser2);
.send(testUser3);

const badCookie = res.header["set-cookie"];

Expand Down
8 changes: 6 additions & 2 deletions packages/api-v2/test/student/student.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@ import { Connection } from "typeorm";
import { dropStudentTable, initializeApp } from "../../test/utils";
import { onboardedUser, testPlan, testUser1 } from "../../test/testingData";

jest.useRealTimers();
jest.setTimeout(10000);

describe("StudentController (e2e)", () => {
let app: INestApplication;
let cookie: any;
let connection: Connection;
let uuid: string;

beforeEach(async () => {
beforeAll(async () => {
app = await initializeApp();

connection = app.get(Connection);
Expand All @@ -26,12 +29,13 @@ describe("StudentController (e2e)", () => {
uuid = res.body.uuid;
});

afterEach(async () => {
afterAll(async () => {
await dropStudentTable(connection);
});

afterAll(async () => {
await app.close();
await connection.close();
});

it("should successfully get a student", async () => {
Expand Down
Loading

0 comments on commit c39223e

Please sign in to comment.