diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 1b5b624..44f4ba2 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -2,6 +2,8 @@ name: testing on: push: branches: [main] + pull_request: + branches: [main] jobs: lint: diff --git a/prisma/initial_data.ts b/prisma/initial_data.ts index ecf0a7c..5df1126 100644 --- a/prisma/initial_data.ts +++ b/prisma/initial_data.ts @@ -1,4 +1,4 @@ -import type { CategorySlug } from "generated/prisma/client.js"; +import type { CategorySlug } from "@/../generated/prisma/client"; export const categories = [ { diff --git a/prisma/seed.ts b/prisma/seed.ts index 655d905..4f35637 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,5 +1,6 @@ import { categories, products } from "./initial_data"; -import { PrismaClient } from "../generated/prisma/client.js"; + +import { PrismaClient } from "@/../generated/prisma/client"; const prisma = new PrismaClient(); diff --git a/src/db/prisma.ts b/src/db/prisma.ts index 7b8438f..b4effae 100644 --- a/src/db/prisma.ts +++ b/src/db/prisma.ts @@ -1,4 +1,4 @@ -import { PrismaClient } from "generated/prisma/client.js"; +import { PrismaClient } from "@/../generated/prisma/client"; // Global variable to store the Prisma client instance declare global { diff --git a/src/e2e/example.spec.ts b/src/e2e/example.spec.ts deleted file mode 100644 index 54a906a..0000000 --- a/src/e2e/example.spec.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { test, expect } from '@playwright/test'; - -test('has title', async ({ page }) => { - await page.goto('https://playwright.dev/'); - - // Expect a title "to contain" a substring. - await expect(page).toHaveTitle(/Playwright/); -}); - -test('get started link', async ({ page }) => { - await page.goto('https://playwright.dev/'); - - // Click the get started link. - await page.getByRole('link', { name: 'Get started' }).click(); - - // Expects page to have a heading with the name of Installation. - await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible(); -}); diff --git a/src/lib/utils.tests.ts b/src/lib/utils.tests.ts index be9f7bb..cb6ce33 100644 --- a/src/lib/utils.tests.ts +++ b/src/lib/utils.tests.ts @@ -5,8 +5,15 @@ import type { Order, OrderDetails, OrderItem } from "@/models/order.model"; import type { Product } from "@/models/product.model"; import type { User } from "@/models/user.model"; +import type { + OrderItem as PrismaOrderItem, + Order as PrismaOrder, + Product as PrismaProduct, +} from "@/../generated/prisma/client"; import type { Session } from "react-router"; +import { Decimal } from "@/../generated/prisma/internal/prismaNamespace"; + type TestRequestConfig = { url?: string; headers?: HeadersInit; @@ -61,6 +68,23 @@ export const createTestProduct = (overrides?: Partial): Product => ({ ...overrides, }); +export const createTestDBProduct = ( + overrides?: Partial +): PrismaProduct => ({ + id: 1, + title: "Test Product", + imgSrc: "/test-image.jpg", + alt: "Test alt text", + price: new Decimal(100), + description: "Test description", + categoryId: 1, + isOnSale: false, + features: ["Feature 1", "Feature 2"], + createdAt: new Date(), + updatedAt: new Date(), + ...overrides, +}); + export const createTestCategory = ( overrides?: Partial ): Category => ({ @@ -107,6 +131,22 @@ export const createTestOrderItem = ( ...overrides, } satisfies OrderItem); +export const createTestDBOrderItem = ( + overrides: Partial = {} +): PrismaOrderItem => + ({ + id: 1, + orderId: 1, + productId: 1, + quantity: 1, + title: "Test Product", + price: new Decimal(100), + imgSrc: "test-image.jpg", + createdAt: new Date(), + updatedAt: new Date(), + ...overrides, + } satisfies PrismaOrderItem); + export const createTestOrder = (overrides: Partial = {}): Order => { const details = overrides.details ?? createTestOrderDetails(); return { @@ -121,3 +161,26 @@ export const createTestOrder = (overrides: Partial = {}): Order => { ...overrides, } satisfies Order; }; + +export const createTestDBOrder = ( + overrides: Partial = {} +): PrismaOrder => { + return { + id: 1, + userId: 1, + email: "test@mail.com", + totalAmount: new Decimal(100), + firstName: "Test", + lastName: "User", + company: null, + address: "Test Address", + city: "Test City", + country: "Test Country", + region: "Test Region", + zip: "12345", + phone: "123456789", + createdAt: new Date(), + updatedAt: new Date(), + ...overrides, + } satisfies PrismaOrder; +}; diff --git a/src/models/cart.model.ts b/src/models/cart.model.ts index 90b62f9..ad4206a 100644 --- a/src/models/cart.model.ts +++ b/src/models/cart.model.ts @@ -3,7 +3,7 @@ import { type Product } from "./product.model"; import type { Cart as PrismaCart, CartItem as PrismaCartItem, -} from "generated/prisma/client"; +} from "@/../generated/prisma/client"; export type CartItem = PrismaCartItem & { product: Pick< diff --git a/src/models/category.model.ts b/src/models/category.model.ts index 594575e..9c05ae1 100644 --- a/src/models/category.model.ts +++ b/src/models/category.model.ts @@ -1,4 +1,4 @@ -import type { Category as PrismaCategory } from "generated/prisma/client"; +import type { Category as PrismaCategory } from "@/../generated/prisma/client"; export const VALID_SLUGS = ["polos", "stickers", "tazas"] as const; diff --git a/src/models/order.model.ts b/src/models/order.model.ts index d2d5c40..3ac10a4 100644 --- a/src/models/order.model.ts +++ b/src/models/order.model.ts @@ -1,7 +1,7 @@ import type { Order as PrismaOrder, OrderItem as PrismaOrderItem, -} from "generated/prisma/client"; +} from "@/../generated/prisma/client"; export type OrderDetails = Pick< PrismaOrder, diff --git a/src/models/product.model.ts b/src/models/product.model.ts index 6f46237..96ba043 100644 --- a/src/models/product.model.ts +++ b/src/models/product.model.ts @@ -1,4 +1,4 @@ -import type { Product as PrismaProduct } from "generated/prisma/client"; +import type { Product as PrismaProduct } from "@/../generated/prisma/client"; export type Product = Omit & { price: number; diff --git a/src/models/user.model.ts b/src/models/user.model.ts index f88c5b6..9662c14 100644 --- a/src/models/user.model.ts +++ b/src/models/user.model.ts @@ -1,4 +1,4 @@ -import type { User as PrismaUser } from "generated/prisma/client"; +import type { User as PrismaUser } from "@/../generated/prisma/client"; export type User = PrismaUser; diff --git a/src/routes/order-confirmation/order-confirmation.test.tsx b/src/routes/order-confirmation/order-confirmation.test.tsx index becd17c..c177020 100644 --- a/src/routes/order-confirmation/order-confirmation.test.tsx +++ b/src/routes/order-confirmation/order-confirmation.test.tsx @@ -1,14 +1,16 @@ import { render, screen } from "@testing-library/react"; -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, it } from "vitest"; import OrderConfirmation from "."; + import type { Route } from "./+types"; // Creates minimal test props for OrderConfirmation component const createTestProps = (orderId = "test-123"): Route.ComponentProps => ({ loaderData: { orderId }, - params: vi.fn() as any, - matches: vi.fn() as any, + params: { orderId }, + // Hack to satisfy type requirements + matches: [] as unknown as Route.ComponentProps["matches"], }); describe("OrderConfirmation", () => { diff --git a/src/routes/product/product.test.tsx b/src/routes/product/product.test.tsx index 3d0bbee..fe59644 100644 --- a/src/routes/product/product.test.tsx +++ b/src/routes/product/product.test.tsx @@ -11,7 +11,7 @@ import type { Route } from "./+types"; // Helper function to create a test navigation object const createTestNavigation = (overrides = {}) => ({ - state: "idle", + state: "idle" as const, location: undefined, formMethod: undefined, formAction: undefined, @@ -33,8 +33,9 @@ const createTestProps = ( productData: Partial = {} ): Route.ComponentProps => ({ loaderData: { product: createTestProduct(productData) }, - params: vi.fn() as any, - matches: vi.fn() as any, + params: { id: "123" }, + // Hack to satisfy type requirements + matches: [] as unknown as Route.ComponentProps["matches"], }); describe("Product Component", () => { @@ -133,7 +134,7 @@ describe("Product Component", () => { const props = createTestProps(); const expectedNavigation = createTestNavigation({ state: "submitting" }); // Step 2: Mock - Override navigation state to simulate loading - vi.mocked(useNavigation).mockReturnValue(expectedNavigation as any); + vi.mocked(useNavigation).mockReturnValue(expectedNavigation); // Step 3: Call render(); // Step 4: Verify diff --git a/src/services/category.service.test.ts b/src/services/category.service.test.ts index 3e434cc..72cd295 100644 --- a/src/services/category.service.test.ts +++ b/src/services/category.service.test.ts @@ -1,21 +1,19 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import { prisma as mockPrisma } from "@/db/prisma"; import { createTestCategory } from "@/lib/utils.tests"; import { getAllCategories, getCategoryBySlug, } from "@/services/category.service"; -// Mock Prisma client -const mockPrisma = { - category: { - findMany: vi.fn(), - findUnique: vi.fn(), - }, -}; - vi.mock("@/db/prisma", () => ({ - prisma: mockPrisma, + prisma: { + category: { + findMany: vi.fn(), + findUnique: vi.fn(), + }, + }, })); describe("Category Service", () => { @@ -38,7 +36,7 @@ describe("Category Service", () => { }), ]; - mockPrisma.category.findMany.mockResolvedValue(mockCategories); + vi.mocked(mockPrisma.category.findMany).mockResolvedValue(mockCategories); const result = await getAllCategories(); @@ -47,7 +45,7 @@ describe("Category Service", () => { }); it("should handle empty categories", async () => { - mockPrisma.category.findMany.mockResolvedValue([]); + vi.mocked(mockPrisma.category.findMany).mockResolvedValue([]); const result = await getAllCategories(); @@ -60,7 +58,7 @@ describe("Category Service", () => { it("should return category when found", async () => { const mockCategory = createTestCategory(); - mockPrisma.category.findUnique.mockResolvedValue(mockCategory); + vi.mocked(mockPrisma.category.findUnique).mockResolvedValue(mockCategory); const result = await getCategoryBySlug("polos"); @@ -71,7 +69,7 @@ describe("Category Service", () => { }); it("should throw error when category not found", async () => { - mockPrisma.category.findUnique.mockResolvedValue(null); + vi.mocked(mockPrisma.category.findUnique).mockResolvedValue(null); await expect(getCategoryBySlug("polos")).rejects.toThrow( 'Category with slug "polos" not found' diff --git a/src/services/category.service.ts b/src/services/category.service.ts index 87d1c96..55924a8 100644 --- a/src/services/category.service.ts +++ b/src/services/category.service.ts @@ -1,7 +1,7 @@ -import { type Category, type CategorySlug } from "generated/prisma/client.js"; - import { prisma } from "@/db/prisma"; +import { type Category, type CategorySlug } from "@/../generated/prisma/client"; + export async function getAllCategories(): Promise { const categories = await prisma.category.findMany(); return categories; diff --git a/src/services/order.service.test.ts b/src/services/order.service.test.ts index f6bcf52..22f80e6 100644 --- a/src/services/order.service.test.ts +++ b/src/services/order.service.test.ts @@ -1,9 +1,11 @@ import { describe, expect, it, vi } from "vitest"; +import { prisma as mockPrisma } from "@/db/prisma"; import { calculateTotal } from "@/lib/cart"; import { createMockSession, - createTestOrder, + createTestDBOrder, + createTestDBOrderItem, createTestOrderDetails, createTestOrderItem, createTestRequest, @@ -15,16 +17,13 @@ import { getSession } from "@/session.server"; import { createOrder, getOrdersByUser } from "./order.service"; import { getOrCreateUser } from "./user.service"; -// Mock Prisma client -const mockPrisma = { - order: { - create: vi.fn(), - findMany: vi.fn(), - }, -}; - vi.mock("@/db/prisma", () => ({ - prisma: mockPrisma, + prisma: { + order: { + create: vi.fn(), + findMany: vi.fn(), + }, + }, })); vi.mock("./user.service"); @@ -56,12 +55,15 @@ describe("Order Service", () => { it("should create an order", async () => { const prismaOrder = { - ...createTestOrder(), - items: [createTestOrderItem()], + ...createTestDBOrder(), + items: [createTestDBOrderItem()], }; + vi.mocked(getOrCreateUser).mockResolvedValue(mockedUser); vi.mocked(calculateTotal).mockReturnValue(mockedTotalAmount); - mockPrisma.order.create.mockResolvedValue(prismaOrder); + + vi.mocked(mockPrisma.order.create).mockResolvedValue(prismaOrder); + const order = await createOrder(mockedItems, mockedFormData); expect(mockPrisma.order.create).toHaveBeenCalledWith({ data: { @@ -94,7 +96,7 @@ describe("Order Service", () => { expect(order).toEqual({ ...prismaOrder, totalAmount: Number(prismaOrder.totalAmount), - items: prismaOrder.items.map((item: any) => ({ + items: prismaOrder.items.map((item) => ({ ...item, price: Number(item.price), imgSrc: item.imgSrc ?? "", @@ -121,15 +123,15 @@ describe("Order Service", () => { it("should get orders by user", async () => { const prismaOrders = [ - { ...createTestOrder(), items: [createTestOrderItem()] }, + { ...createTestDBOrder(), items: [createTestOrderItem()] }, { - ...createTestOrder({ id: 2 }), + ...createTestDBOrder({ id: 2 }), items: [createTestOrderItem({ id: 2 })], }, ]; const mockedSession = createMockSession(mockedUser.id); vi.mocked(getSession).mockResolvedValue(mockedSession); - mockPrisma.order.findMany.mockResolvedValue(prismaOrders); + vi.mocked(mockPrisma.order.findMany).mockResolvedValue(prismaOrders); const orders = await getOrdersByUser(mockedRequest); expect(mockPrisma.order.findMany).toHaveBeenCalledWith({ where: { userId: mockedUser.id }, @@ -140,7 +142,7 @@ describe("Order Service", () => { prismaOrders.map((order) => ({ ...order, totalAmount: Number(order.totalAmount), - items: order.items.map((item: any) => ({ + items: order.items.map((item) => ({ ...item, price: Number(item.price), imgSrc: item.imgSrc ?? "", @@ -181,7 +183,9 @@ describe("Order Service", () => { it("should throw error if order creation fails", async () => { vi.mocked(getOrCreateUser).mockResolvedValue(mockedUser); vi.mocked(calculateTotal).mockReturnValue(mockedTotalAmount); - mockPrisma.order.create.mockResolvedValue(null); + vi.mocked(mockPrisma.order.create).mockRejectedValue( + new Error("Database error") + ); await expect(createOrder(mockedItems, mockedFormData)).rejects.toThrow( "Failed to create order" diff --git a/src/services/order.service.ts b/src/services/order.service.ts index 99f7623..f29f93d 100644 --- a/src/services/order.service.ts +++ b/src/services/order.service.ts @@ -13,26 +13,33 @@ export async function createOrder( const shippingDetails = formData; const user = await getOrCreateUser(shippingDetails.email); const totalAmount = calculateTotal(items); - const order = await prisma.order.create({ - data: { - userId: user.id, - totalAmount: totalAmount, - ...shippingDetails, - items: { - create: items.map((item) => ({ - productId: item.productId, - quantity: item.quantity, - title: item.title, - price: item.price, - imgSrc: item.imgSrc, - })), + + let order; + + try { + order = await prisma.order.create({ + data: { + userId: user.id, + totalAmount: totalAmount, + ...shippingDetails, + items: { + create: items.map((item) => ({ + productId: item.productId, + quantity: item.quantity, + title: item.title, + price: item.price, + imgSrc: item.imgSrc, + })), + }, }, - }, - include: { - items: true, - }, - }); - if (!order) throw new Error("Failed to create order"); + include: { + items: true, + }, + }); + } catch (error) { + throw new Error("Failed to create order", { cause: error }); + } + const details = { email: order.email, firstName: order.firstName, diff --git a/src/services/product.service.test.ts b/src/services/product.service.test.ts index 721b428..7bac27a 100644 --- a/src/services/product.service.test.ts +++ b/src/services/product.service.test.ts @@ -1,22 +1,21 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; -import { createTestCategory, createTestProduct } from "@/lib/utils.tests"; +import { prisma as mockPrisma } from "@/db/prisma"; +import { createTestCategory, createTestDBProduct } from "@/lib/utils.tests"; import type { Category } from "@/models/category.model"; -import type { Product } from "@/models/product.model"; import { getCategoryBySlug } from "./category.service"; import { getProductById, getProductsByCategorySlug } from "./product.service"; -// Mock Prisma client -const mockPrisma = { - product: { - findMany: vi.fn(), - findUnique: vi.fn(), - }, -}; +import type { Product as PrismaProduct } from "@/../generated/prisma/client"; vi.mock("@/db/prisma", () => ({ - prisma: mockPrisma, + prisma: { + product: { + findMany: vi.fn(), + findUnique: vi.fn(), + }, + }, })); // Mock category service @@ -31,9 +30,9 @@ describe("Product Service", () => { it("should return products for a valid category slug", async () => { // Step 1: Setup - Create test data with valid category and products const testCategory = createTestCategory(); - const mockedProducts: Product[] = [ - createTestProduct({ id: 1, categoryId: testCategory.id }), - createTestProduct({ + const mockedProducts: PrismaProduct[] = [ + createTestDBProduct({ id: 1, categoryId: testCategory.id }), + createTestDBProduct({ id: 2, title: "Test Product 2", categoryId: testCategory.id, @@ -42,7 +41,8 @@ describe("Product Service", () => { // Step 2: Mock - Configure responses vi.mocked(getCategoryBySlug).mockResolvedValue(testCategory); - mockPrisma.product.findMany.mockResolvedValue(mockedProducts); + + vi.mocked(mockPrisma.product.findMany).mockResolvedValue(mockedProducts); // Step 3: Call service function const products = await getProductsByCategorySlug(testCategory.slug); @@ -52,7 +52,12 @@ describe("Product Service", () => { expect(mockPrisma.product.findMany).toHaveBeenCalledWith({ where: { categoryId: testCategory.id }, }); - expect(products).toEqual(mockedProducts); + expect(products).toEqual( + mockedProducts.map((product) => ({ + ...product, + price: product.price.toNumber(), + })) + ); }); it("should throw error when category slug does not exist", async () => { @@ -77,10 +82,10 @@ describe("Product Service", () => { describe("getProductById", () => { it("should return product for valid ID", async () => { // Step 1: Setup - Create test data for existing product - const testProduct = createTestProduct(); + const testProduct = createTestDBProduct(); // Step 2: Mock - Configure Prisma response - mockPrisma.product.findUnique.mockResolvedValue(testProduct); + vi.mocked(mockPrisma.product.findUnique).mockResolvedValue(testProduct); // Step 3: Call service function const result = await getProductById(testProduct.id); @@ -89,7 +94,10 @@ describe("Product Service", () => { expect(mockPrisma.product.findUnique).toHaveBeenCalledWith({ where: { id: testProduct.id }, }); - expect(result).toEqual(testProduct); + expect(result).toEqual({ + ...testProduct, + price: testProduct.price.toNumber(), + }); }); it("should throw error when product does not exist", async () => { @@ -97,7 +105,7 @@ describe("Product Service", () => { const nonExistentId = 999; // Step 2: Mock - Configure null response from Prisma - mockPrisma.product.findUnique.mockResolvedValue(null); + vi.mocked(mockPrisma.product.findUnique).mockResolvedValue(null); // Step 3: Call service function const productPromise = getProductById(nonExistentId); diff --git a/src/services/user.service.test.ts b/src/services/user.service.test.ts index dc69ff3..c5c7b5b 100644 --- a/src/services/user.service.test.ts +++ b/src/services/user.service.test.ts @@ -40,9 +40,11 @@ describe("user service", () => { vi.mocked(prisma.user.update).mockResolvedValue(updatedUser); vi.mocked(getSession).mockResolvedValue(mockSession); + const { password: _password, ...expectedUser } = updatedUser; + // Llamando al servicio y verificando el resultado expect(await userService.updateUser(updatedUser, request)).toEqual( - updatedUser + expectedUser ); }); @@ -68,8 +70,6 @@ describe("user service", () => { await userService.updateUser(updatedUser, request); expect(hashPassword).toHaveBeenCalledWith(passwordBeforeHashing); // Verifica que se haya llamado a hashPassword con la contraseña original - expect(updatedUser.password).not.toBe(passwordBeforeHashing); // Verifica que la contraseña se haya actualizado - expect(updatedUser.password).toBe("hashed-password"); // Verifica que la contraseña se haya actualizado }); it("should throw error if user is not authenticated", async () => { diff --git a/src/services/user.service.ts b/src/services/user.service.ts index b20e923..94d62bd 100644 --- a/src/services/user.service.ts +++ b/src/services/user.service.ts @@ -1,6 +1,6 @@ +import { prisma } from "@/db/prisma"; import { hashPassword } from "@/lib/security"; import type { User, AuthResponse } from "@/models/user.model"; -import { prisma } from "@/db/prisma"; import { getSession } from "@/session.server"; export async function updateUser( @@ -14,19 +14,20 @@ export async function updateUser( throw new Error("User not authenticated"); } - const data = { ...updatedUser } as any; + const data = { ...updatedUser }; if (updatedUser.password) { const hashedPassword = await hashPassword(updatedUser.password); data.password = hashedPassword; } - const userData = await prisma.user.update({ - where: { id: typeof id === "number" ? id : Number(id) }, - data, - }); + const { password: _password, ...userWithoutPassword } = + await prisma.user.update({ + where: { id: typeof id === "number" ? id : Number(id) }, + data, + }); - return userData; + return userWithoutPassword; } export async function getOrCreateUser(email: string): Promise { diff --git a/tests-examples/demo-todo-app.spec.ts b/tests-examples/demo-todo-app.spec.ts deleted file mode 100644 index 8641cb5..0000000 --- a/tests-examples/demo-todo-app.spec.ts +++ /dev/null @@ -1,437 +0,0 @@ -import { test, expect, type Page } from '@playwright/test'; - -test.beforeEach(async ({ page }) => { - await page.goto('https://demo.playwright.dev/todomvc'); -}); - -const TODO_ITEMS = [ - 'buy some cheese', - 'feed the cat', - 'book a doctors appointment' -] as const; - -test.describe('New Todo', () => { - test('should allow me to add todo items', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - // Create 1st todo. - await newTodo.fill(TODO_ITEMS[0]); - await newTodo.press('Enter'); - - // Make sure the list only has one todo item. - await expect(page.getByTestId('todo-title')).toHaveText([ - TODO_ITEMS[0] - ]); - - // Create 2nd todo. - await newTodo.fill(TODO_ITEMS[1]); - await newTodo.press('Enter'); - - // Make sure the list now has two todo items. - await expect(page.getByTestId('todo-title')).toHaveText([ - TODO_ITEMS[0], - TODO_ITEMS[1] - ]); - - await checkNumberOfTodosInLocalStorage(page, 2); - }); - - test('should clear text input field when an item is added', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - // Create one todo item. - await newTodo.fill(TODO_ITEMS[0]); - await newTodo.press('Enter'); - - // Check that input is empty. - await expect(newTodo).toBeEmpty(); - await checkNumberOfTodosInLocalStorage(page, 1); - }); - - test('should append new items to the bottom of the list', async ({ page }) => { - // Create 3 items. - await createDefaultTodos(page); - - // create a todo count locator - const todoCount = page.getByTestId('todo-count') - - // Check test using different methods. - await expect(page.getByText('3 items left')).toBeVisible(); - await expect(todoCount).toHaveText('3 items left'); - await expect(todoCount).toContainText('3'); - await expect(todoCount).toHaveText(/3/); - - // Check all items in one call. - await expect(page.getByTestId('todo-title')).toHaveText(TODO_ITEMS); - await checkNumberOfTodosInLocalStorage(page, 3); - }); -}); - -test.describe('Mark all as completed', () => { - test.beforeEach(async ({ page }) => { - await createDefaultTodos(page); - await checkNumberOfTodosInLocalStorage(page, 3); - }); - - test.afterEach(async ({ page }) => { - await checkNumberOfTodosInLocalStorage(page, 3); - }); - - test('should allow me to mark all items as completed', async ({ page }) => { - // Complete all todos. - await page.getByLabel('Mark all as complete').check(); - - // Ensure all todos have 'completed' class. - await expect(page.getByTestId('todo-item')).toHaveClass(['completed', 'completed', 'completed']); - await checkNumberOfCompletedTodosInLocalStorage(page, 3); - }); - - test('should allow me to clear the complete state of all items', async ({ page }) => { - const toggleAll = page.getByLabel('Mark all as complete'); - // Check and then immediately uncheck. - await toggleAll.check(); - await toggleAll.uncheck(); - - // Should be no completed classes. - await expect(page.getByTestId('todo-item')).toHaveClass(['', '', '']); - }); - - test('complete all checkbox should update state when items are completed / cleared', async ({ page }) => { - const toggleAll = page.getByLabel('Mark all as complete'); - await toggleAll.check(); - await expect(toggleAll).toBeChecked(); - await checkNumberOfCompletedTodosInLocalStorage(page, 3); - - // Uncheck first todo. - const firstTodo = page.getByTestId('todo-item').nth(0); - await firstTodo.getByRole('checkbox').uncheck(); - - // Reuse toggleAll locator and make sure its not checked. - await expect(toggleAll).not.toBeChecked(); - - await firstTodo.getByRole('checkbox').check(); - await checkNumberOfCompletedTodosInLocalStorage(page, 3); - - // Assert the toggle all is checked again. - await expect(toggleAll).toBeChecked(); - }); -}); - -test.describe('Item', () => { - - test('should allow me to mark items as complete', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - // Create two items. - for (const item of TODO_ITEMS.slice(0, 2)) { - await newTodo.fill(item); - await newTodo.press('Enter'); - } - - // Check first item. - const firstTodo = page.getByTestId('todo-item').nth(0); - await firstTodo.getByRole('checkbox').check(); - await expect(firstTodo).toHaveClass('completed'); - - // Check second item. - const secondTodo = page.getByTestId('todo-item').nth(1); - await expect(secondTodo).not.toHaveClass('completed'); - await secondTodo.getByRole('checkbox').check(); - - // Assert completed class. - await expect(firstTodo).toHaveClass('completed'); - await expect(secondTodo).toHaveClass('completed'); - }); - - test('should allow me to un-mark items as complete', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - // Create two items. - for (const item of TODO_ITEMS.slice(0, 2)) { - await newTodo.fill(item); - await newTodo.press('Enter'); - } - - const firstTodo = page.getByTestId('todo-item').nth(0); - const secondTodo = page.getByTestId('todo-item').nth(1); - const firstTodoCheckbox = firstTodo.getByRole('checkbox'); - - await firstTodoCheckbox.check(); - await expect(firstTodo).toHaveClass('completed'); - await expect(secondTodo).not.toHaveClass('completed'); - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - - await firstTodoCheckbox.uncheck(); - await expect(firstTodo).not.toHaveClass('completed'); - await expect(secondTodo).not.toHaveClass('completed'); - await checkNumberOfCompletedTodosInLocalStorage(page, 0); - }); - - test('should allow me to edit an item', async ({ page }) => { - await createDefaultTodos(page); - - const todoItems = page.getByTestId('todo-item'); - const secondTodo = todoItems.nth(1); - await secondTodo.dblclick(); - await expect(secondTodo.getByRole('textbox', { name: 'Edit' })).toHaveValue(TODO_ITEMS[1]); - await secondTodo.getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); - await secondTodo.getByRole('textbox', { name: 'Edit' }).press('Enter'); - - // Explicitly assert the new text value. - await expect(todoItems).toHaveText([ - TODO_ITEMS[0], - 'buy some sausages', - TODO_ITEMS[2] - ]); - await checkTodosInLocalStorage(page, 'buy some sausages'); - }); -}); - -test.describe('Editing', () => { - test.beforeEach(async ({ page }) => { - await createDefaultTodos(page); - await checkNumberOfTodosInLocalStorage(page, 3); - }); - - test('should hide other controls when editing', async ({ page }) => { - const todoItem = page.getByTestId('todo-item').nth(1); - await todoItem.dblclick(); - await expect(todoItem.getByRole('checkbox')).not.toBeVisible(); - await expect(todoItem.locator('label', { - hasText: TODO_ITEMS[1], - })).not.toBeVisible(); - await checkNumberOfTodosInLocalStorage(page, 3); - }); - - test('should save edits on blur', async ({ page }) => { - const todoItems = page.getByTestId('todo-item'); - await todoItems.nth(1).dblclick(); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).dispatchEvent('blur'); - - await expect(todoItems).toHaveText([ - TODO_ITEMS[0], - 'buy some sausages', - TODO_ITEMS[2], - ]); - await checkTodosInLocalStorage(page, 'buy some sausages'); - }); - - test('should trim entered text', async ({ page }) => { - const todoItems = page.getByTestId('todo-item'); - await todoItems.nth(1).dblclick(); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(' buy some sausages '); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter'); - - await expect(todoItems).toHaveText([ - TODO_ITEMS[0], - 'buy some sausages', - TODO_ITEMS[2], - ]); - await checkTodosInLocalStorage(page, 'buy some sausages'); - }); - - test('should remove the item if an empty text string was entered', async ({ page }) => { - const todoItems = page.getByTestId('todo-item'); - await todoItems.nth(1).dblclick(); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill(''); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Enter'); - - await expect(todoItems).toHaveText([ - TODO_ITEMS[0], - TODO_ITEMS[2], - ]); - }); - - test('should cancel edits on escape', async ({ page }) => { - const todoItems = page.getByTestId('todo-item'); - await todoItems.nth(1).dblclick(); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).fill('buy some sausages'); - await todoItems.nth(1).getByRole('textbox', { name: 'Edit' }).press('Escape'); - await expect(todoItems).toHaveText(TODO_ITEMS); - }); -}); - -test.describe('Counter', () => { - test('should display the current number of todo items', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - // create a todo count locator - const todoCount = page.getByTestId('todo-count') - - await newTodo.fill(TODO_ITEMS[0]); - await newTodo.press('Enter'); - - await expect(todoCount).toContainText('1'); - - await newTodo.fill(TODO_ITEMS[1]); - await newTodo.press('Enter'); - await expect(todoCount).toContainText('2'); - - await checkNumberOfTodosInLocalStorage(page, 2); - }); -}); - -test.describe('Clear completed button', () => { - test.beforeEach(async ({ page }) => { - await createDefaultTodos(page); - }); - - test('should display the correct text', async ({ page }) => { - await page.locator('.todo-list li .toggle').first().check(); - await expect(page.getByRole('button', { name: 'Clear completed' })).toBeVisible(); - }); - - test('should remove completed items when clicked', async ({ page }) => { - const todoItems = page.getByTestId('todo-item'); - await todoItems.nth(1).getByRole('checkbox').check(); - await page.getByRole('button', { name: 'Clear completed' }).click(); - await expect(todoItems).toHaveCount(2); - await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]); - }); - - test('should be hidden when there are no items that are completed', async ({ page }) => { - await page.locator('.todo-list li .toggle').first().check(); - await page.getByRole('button', { name: 'Clear completed' }).click(); - await expect(page.getByRole('button', { name: 'Clear completed' })).toBeHidden(); - }); -}); - -test.describe('Persistence', () => { - test('should persist its data', async ({ page }) => { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - for (const item of TODO_ITEMS.slice(0, 2)) { - await newTodo.fill(item); - await newTodo.press('Enter'); - } - - const todoItems = page.getByTestId('todo-item'); - const firstTodoCheck = todoItems.nth(0).getByRole('checkbox'); - await firstTodoCheck.check(); - await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]); - await expect(firstTodoCheck).toBeChecked(); - await expect(todoItems).toHaveClass(['completed', '']); - - // Ensure there is 1 completed item. - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - - // Now reload. - await page.reload(); - await expect(todoItems).toHaveText([TODO_ITEMS[0], TODO_ITEMS[1]]); - await expect(firstTodoCheck).toBeChecked(); - await expect(todoItems).toHaveClass(['completed', '']); - }); -}); - -test.describe('Routing', () => { - test.beforeEach(async ({ page }) => { - await createDefaultTodos(page); - // make sure the app had a chance to save updated todos in storage - // before navigating to a new view, otherwise the items can get lost :( - // in some frameworks like Durandal - await checkTodosInLocalStorage(page, TODO_ITEMS[0]); - }); - - test('should allow me to display active items', async ({ page }) => { - const todoItem = page.getByTestId('todo-item'); - await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); - - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - await page.getByRole('link', { name: 'Active' }).click(); - await expect(todoItem).toHaveCount(2); - await expect(todoItem).toHaveText([TODO_ITEMS[0], TODO_ITEMS[2]]); - }); - - test('should respect the back button', async ({ page }) => { - const todoItem = page.getByTestId('todo-item'); - await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); - - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - - await test.step('Showing all items', async () => { - await page.getByRole('link', { name: 'All' }).click(); - await expect(todoItem).toHaveCount(3); - }); - - await test.step('Showing active items', async () => { - await page.getByRole('link', { name: 'Active' }).click(); - }); - - await test.step('Showing completed items', async () => { - await page.getByRole('link', { name: 'Completed' }).click(); - }); - - await expect(todoItem).toHaveCount(1); - await page.goBack(); - await expect(todoItem).toHaveCount(2); - await page.goBack(); - await expect(todoItem).toHaveCount(3); - }); - - test('should allow me to display completed items', async ({ page }) => { - await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - await page.getByRole('link', { name: 'Completed' }).click(); - await expect(page.getByTestId('todo-item')).toHaveCount(1); - }); - - test('should allow me to display all items', async ({ page }) => { - await page.getByTestId('todo-item').nth(1).getByRole('checkbox').check(); - await checkNumberOfCompletedTodosInLocalStorage(page, 1); - await page.getByRole('link', { name: 'Active' }).click(); - await page.getByRole('link', { name: 'Completed' }).click(); - await page.getByRole('link', { name: 'All' }).click(); - await expect(page.getByTestId('todo-item')).toHaveCount(3); - }); - - test('should highlight the currently applied filter', async ({ page }) => { - await expect(page.getByRole('link', { name: 'All' })).toHaveClass('selected'); - - //create locators for active and completed links - const activeLink = page.getByRole('link', { name: 'Active' }); - const completedLink = page.getByRole('link', { name: 'Completed' }); - await activeLink.click(); - - // Page change - active items. - await expect(activeLink).toHaveClass('selected'); - await completedLink.click(); - - // Page change - completed items. - await expect(completedLink).toHaveClass('selected'); - }); -}); - -async function createDefaultTodos(page: Page) { - // create a new todo locator - const newTodo = page.getByPlaceholder('What needs to be done?'); - - for (const item of TODO_ITEMS) { - await newTodo.fill(item); - await newTodo.press('Enter'); - } -} - -async function checkNumberOfTodosInLocalStorage(page: Page, expected: number) { - return await page.waitForFunction(e => { - return JSON.parse(localStorage['react-todos']).length === e; - }, expected); -} - -async function checkNumberOfCompletedTodosInLocalStorage(page: Page, expected: number) { - return await page.waitForFunction(e => { - return JSON.parse(localStorage['react-todos']).filter((todo: any) => todo.completed).length === e; - }, expected); -} - -async function checkTodosInLocalStorage(page: Page, title: string) { - return await page.waitForFunction(t => { - return JSON.parse(localStorage['react-todos']).map((todo: any) => todo.title).includes(t); - }, title); -} diff --git a/vitest.config.ts b/vitest.config.ts index 44c2a13..7685ba2 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -7,6 +7,7 @@ export default defineConfig({ globals: true, environment: "jsdom", setupFiles: ["./vitest.setup.ts"], + exclude: ["**/e2e/**", "**/node_modules/**"], }, resolve: { alias: {