Skip to content

Commit

Permalink
feat: LC-62 add e2e test to categories controller
Browse files Browse the repository at this point in the history
  • Loading branch information
tomaszbilka committed Aug 14, 2024
1 parent 2e82d4a commit 3cac9ff
Show file tree
Hide file tree
Showing 5 changed files with 135 additions and 5 deletions.
103 changes: 103 additions & 0 deletions apps/api/src/categories/__tests__/categories.controller.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { createCategoryFactory } from "../../../test/factory/category.factory";
import { createE2ETest } from "../../../test/create-e2e-test";
import {
createUserFactory,
UserWithCredentials,
} from "../../../test/factory/user.factory";
import { DatabasePg } from "src/common";
import { INestApplication } from "@nestjs/common";
import { UserRole } from "src/users/schemas/user-roles";
import request from "supertest";

const CATEGORIES_COUNT = 10;

describe("CategoriesController (e2e)", () => {
const testPassword = "password123";
let app: INestApplication;
let categoryFactory: ReturnType<typeof createCategoryFactory>;
let db: DatabasePg;
let testUser: UserWithCredentials;
let userFactory: ReturnType<typeof createUserFactory>;

beforeAll(async () => {
const { app: testApp } = await createE2ETest();
app = testApp;
db = app.get("DB");
userFactory = createUserFactory(db);
categoryFactory = createCategoryFactory(db);
Array.from({ length: CATEGORIES_COUNT }, () => categoryFactory.create());
}, 30000);

const getCookie = async (role: UserRole) => {
testUser = await userFactory
.withCredentials({ password: testPassword })
.create({ role });

const loginResponse = await request(app.getHttpServer())
.post("/auth/login")
.send({
email: testUser.email,
password: testUser.credentials?.password,
});

return loginResponse.headers["set-cookie"];
};

describe("POST /categories", () => {
it("should return all categories for student role (only 'id' and 'title')", async () => {
const response = await request(app.getHttpServer())
.get("/categories")
.set("Cookie", await getCookie("student"))
.expect(200);

const responseData = response.body.data;

expect(responseData[0]).toHaveProperty("id");
expect(responseData[0]).toHaveProperty("title");
expect(responseData[0]).not.toHaveProperty("archivedAt");
expect(responseData[0]).not.toHaveProperty("createdAt");
});

it("should return all categories for admin role (all columns)", async () => {
const response = await request(app.getHttpServer())
.get("/categories")
.set("Cookie", await getCookie("admin"))
.expect(200);

const responseData = response.body.data;

expect(responseData[0]).toHaveProperty("id");
expect(responseData[0]).toHaveProperty("title");
expect(responseData[0]).toHaveProperty("archivedAt");
expect(responseData[0]).toHaveProperty("createdAt");
});

it("should pagination work", async () => {
let perPage = 5;
let page = 1;

const response = await request(app.getHttpServer())
.get(`/categories?perPage=${perPage}&page=${page}`)
.set("Cookie", await getCookie("student"))
.expect(200);

const paginationData = response.body.pagination;

expect(response.body.data).toHaveLength(perPage);
expect(paginationData.totalItems).toBe(CATEGORIES_COUNT);
expect(paginationData.page).toBe(page);
expect(paginationData.perPage).toBe(perPage);

perPage = 8;
page = 2;

const res = await request(app.getHttpServer())
.get(`/categories?perPage=${perPage}&page=${page}`)
.set("Cookie", await getCookie("student"))
.expect(200);

expect(res.body.data).toHaveLength(CATEGORIES_COUNT - perPage);
expect(res.body.pagination.totalItems).toBe(CATEGORIES_COUNT);
});
});
});
4 changes: 2 additions & 2 deletions apps/api/src/categories/api/categories.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import {
allCategoriesSchema,
} from "../schemas/category.schema";
import { paginatedResponse, PaginatedResponse } from "src/common";
import { CategorieService } from "../categories.service";
import { CategoriesService } from "../categories.service";
import { CurrentUser } from "src/common/decorators/user.decorator";
import { UserRole } from "src/users/schemas/user-roles";

@Controller("categories")
export class CategorieController {
constructor(private readonly categoriesService: CategorieService) {}
constructor(private readonly categoriesService: CategoriesService) {}

@Get()
@Validate({
Expand Down
4 changes: 2 additions & 2 deletions apps/api/src/categories/categories.module.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { CategorieController } from "./api/categories.controller";
import { CategorieService } from "./categories.service";
import { CategoriesService } from "./categories.service";
import { Module } from "@nestjs/common";

@Module({
imports: [],
controllers: [CategorieController],
providers: [CategorieService],
providers: [CategoriesService],
exports: [],
})
export class CategoriesModule {}
2 changes: 1 addition & 1 deletion apps/api/src/categories/categories.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { DatabasePg } from "src/common";
import { UserRole, UserRoles } from "src/users/schemas/user-roles";

@Injectable()
export class CategorieService {
export class CategoriesService {
constructor(@Inject("DB") private readonly db: DatabasePg) {}

private createLikeFilter(filter: string) {
Expand Down
27 changes: 27 additions & 0 deletions apps/api/test/factory/category.factory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { categories } from "../../src/storage/schema";
import { DatabasePg } from "src/common";
import { Factory } from "fishery";
import { faker } from "@faker-js/faker";
import { InferInsertModel } from "drizzle-orm";

type Category = InferInsertModel<typeof categories>;

export const createCategoryFactory = (db: DatabasePg) => {
return Factory.define<Category>(({ onCreate }) => {
onCreate(async (category) => {
const [inserted] = await db
.insert(categories)
.values(category)
.returning();
return inserted;
});

return {
id: faker.string.uuid(),
title: faker.commerce.department(),
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
archivedAt: null,
};
});
};

0 comments on commit 3cac9ff

Please sign in to comment.