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

feat: e2e tests #113

Merged
merged 8 commits into from
Jun 28, 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
2 changes: 1 addition & 1 deletion app/auth/(logout-guard)/signup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const metadata: Metadata = {
export default function SignupPage() {
return (
<>
<AuthPageTitle title="Crea tu usuario" />
<AuthPageTitle title="Crea tu usuario" testId="signup-title" />
<div className="h-6"></div>
<SignupForm />
</>
Expand Down
6 changes: 6 additions & 0 deletions e2e/landing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expect, test } from "@playwright/test";

test("Has title", async ({ page }) => {
await page.goto("/");
await expect(page).toHaveTitle(/clubmemo/);
});
36 changes: 36 additions & 0 deletions e2e/signup.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import test, { expect } from "@playwright/test";
import { MongoClient, ServerApiVersion } from "mongodb";

const createEmail = (browserName: string) =>
`signup-test-${browserName}@test.com`;

test.beforeEach(async ({ page, browserName }) => {
const mongoClient = new MongoClient(process.env.MONGODB_URL, {
serverApi: {
version: ServerApiVersion.v1,
deprecationErrors: true,
},
});
await mongoClient.connect();
await mongoClient
.db()
.collection("users")
.deleteOne({ email: createEmail(browserName) });
await page.goto("/");
});

test("Sign up with email and password from landing page", async ({
page,
browserName,
}) => {
await page.getByTestId("signup-button-1").click();

let titleText = await page.getByTestId("signup-title").textContent();
expect(titleText).toBe("Crea tu usuario");
await page.getByTestId("email").fill(createEmail(browserName));
await page.getByTestId("password").fill("TestPassword123");
await page.getByTestId("acceptTerms").click();
await page.getByTestId("submit").click();
titleText = await page.getByTestId("verify-email-title").textContent();
expect(titleText).toContain("Ya casi estamos");
});
4 changes: 3 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ setup:
test:
./nvm-exec.sh pnpm test:unit

# Run end-to-end tests
# Run end-to-end tests. For example: just e2e --ui
e2e *args:
./nvm-exec.sh pnpm exec playwright test {{ args }}

e2e-install:
./nvm-exec.sh pnpm exec playwright install

alias i := install
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"csv-stringify": "^6.5.0",
"dayjs": "^1.11.11",
"dompurify": "^3.1.5",
"dotenv": "^16.4.5",
"i18next": "^23.11.5",
"input-otp": "^1.2.4",
"jsdom": "^24.1.0",
Expand Down
21 changes: 15 additions & 6 deletions playwright.config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { defineConfig, devices } from "@playwright/test";
import dotenv from "dotenv";
import path from "path";

let parsed: Record<string, string> | undefined;
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
* Load environment variables
*/
// require('dotenv').config();

if (!process.env.CI) {
parsed = dotenv.config({
path: path.resolve(__dirname, ".env.test.local"),
}).parsed;
}
/**
* See https://playwright.dev/docs/test-configuration.
*/
Expand All @@ -23,8 +28,8 @@ export default defineConfig({
reporter: "html",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
baseURL: "http://127.0.0.1:3000",
/* Base URL to use in actions like `await page.goto('/')`. */
// baseUrl: 'http://127.0.0.1:3000',

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
Expand Down Expand Up @@ -70,9 +75,13 @@ export default defineConfig({

/* Run your local dev server before starting the tests */
webServer: {
command: "pnpm dev",
command: "pnpm run dev",
url: "http://localhost:3000",
timeout: 120 * 1000,
reuseExistingServer: !process.env.CI,
// stdout: "pipe",
env: {
...parsed,
},
},
});
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions src/auth/ui/components/auth-page-title.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@ import { textStyles } from "@/src/common/ui/styles/text-styles";
interface AuthPageTitleProps {
title: string;
description?: string;
testId?: string;
}
/**
* Reusable component that shows the title and description of the page.
* Used in the authentication pages to give them a consistent look.
*/
export function AuthPageTitle({ title, description }: AuthPageTitleProps) {
export function AuthPageTitle({
title,
description,
testId,
}: AuthPageTitleProps) {
return (
<>
<h1 className={textStyles.h2}>{title}</h1>
<h1 data-testid={testId} className={textStyles.h2}>
{title}
</h1>
{description && (
<>
<div className="h-2"></div>
Expand Down
2 changes: 1 addition & 1 deletion src/auth/ui/signup/actions/signup-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export async function signupAction(input: SignupActionModel) {
await useCase.execute(parsed);
} catch (e) {
if (e instanceof UserAlreadyExistsError) {
return ActionResponse.formError("name", {
return ActionResponse.formError("email", {
type: "exists",
message: "A user with this email already exists",
});
Expand Down
1 change: 0 additions & 1 deletion src/auth/ui/signup/components/signup-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import { z } from "@/i18n/zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { FormProvider, useForm } from "react-hook-form";

import { clientLocator } from "@/src/common/di/client-locator";
import { waitMilliseconds } from "@/src/common/domain/utils/promise";
import { EmailSchema } from "@/src/common/schemas/email-schema";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function VerifyEmailPageLoaded({
<div className="h-6"></div>
<AuthPageTitle
title="¡Ya casi estamos!"
testId="verify-email-title"
description={`Te hemos enviado un correo electrónico a ${user.email} con un código de verificación.`}
/>
{hasExpired && (
Expand Down
42 changes: 42 additions & 0 deletions src/common/domain/models/pagination-model.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import type { PaginationModelData } from "./pagination-model";
import { PaginationModel } from "./pagination-model";

describe("PaginationModel", () => {
const paginationModel = new PaginationModel({
results: [1, 2, 3],
totalCount: 10,
});

it("results contains the elements of the paginated list", () => {
expect(paginationModel.results).toEqual([1, 2, 3]);
});

it("totalCount matches data", () => {
expect(paginationModel.totalCount).toEqual(10);
});

it("toData serializes the elements of the results list", () => {
const serialized = paginationModel.toData((data) => data.toString());
expect(serialized.results).toEqual(["1", "2", "3"]);
expect(serialized.totalCount).toEqual(10);
});

it("fromData deserializes the elements of the results list", () => {
const serialized: PaginationModelData<string> = {
results: ["1", "2", "3"],
totalCount: 10,
};
expect(
PaginationModel.fromData(serialized, (element) => parseInt(element))
.results,
).toEqual([1, 2, 3]);
expect(serialized.totalCount).toEqual(10);
});

it("empty returns an empty pagination model", () => {
const empty = PaginationModel.empty();
expect(empty.results).toEqual([]);
expect(empty.totalCount).toEqual(0);
});
});
36 changes: 34 additions & 2 deletions src/common/domain/models/pagination-model.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,72 @@
/**
* Serialized data of `PaginationModel`
*/
export interface PaginationModelData<T> {
results: T[];
totalCount: number;
}

/**
* A paginated list. Contains a fraction of the results of a query.
* It also contains the total count of the results.
*/
export class PaginationModel<T> {
constructor(public readonly data: PaginationModelData<T>) {}

/**
* Elements of the paginated list
*/
get results() {
return this.data.results;
}

/**
* Total count of the results of the query.
* It is equal or larger than the length of the results list.
*/
get totalCount() {
return this.data.totalCount;
}

/**
* Creates an empty pagination model.
*
* @returns An empty pagination model
*/
static empty<T>(): PaginationModel<T> {
return new PaginationModel<T>({
results: [],
totalCount: 0,
});
}

/**
* Creates a serialized version of the pagination model.
*
* @param serializer Function to serialize the elements of the results list
* @returns A serialized version of the pagination model
*/
toData<U>(serializer: (data: T) => U): PaginationModelData<U> {
return {
...this.data,
results: this.results.map(serializer),
totalCount: this.totalCount,
};
}

/**
* Creates a new pagination model from serialized data.
*
* @param data Serialized data
* @param deserializer Function that transforms a serialized element into the original type
* @returns A pagination model with the deserialized elements
*/
static fromData<T, U>(
data: PaginationModelData<U>,
deserializer: (data: U) => T,
): PaginationModel<T> {
return new PaginationModel<T>({
...data,
results: data.results.map(deserializer),
totalCount: data.totalCount,
});
}
}
30 changes: 30 additions & 0 deletions src/common/domain/models/token-pagination-model.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { TokenPaginationModel } from "./token-pagination-model";

describe("TokenPaginationModel", () => {
it("properties match value", () => {
const data = { results: [1, 2, 3], token: "test-token-134" };
const model = new TokenPaginationModel(data);
expect(model.results).toEqual(data.results);
expect(model.token).toEqual(data.token);
});

it("toData serializes data", () => {
const data = { results: [1, 2, 3], token: "testToken" };
const model = new TokenPaginationModel(data);
const serializedData = model.toData((num: number) => num.toString());
expect(serializedData).toEqual({
token: data.token,
results: ["1", "2", "3"],
});
});

it("fromData deserializes data", () => {
const data = { results: ["1", "2", "3"], token: "testToken" };
const model = TokenPaginationModel.fromData(data, (str: string) =>
parseInt(str),
);
expect(model.results).toEqual([1, 2, 3]);
expect(model.token).toEqual(data.token);
});
});
29 changes: 28 additions & 1 deletion src/common/domain/models/token-pagination-model.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,53 @@
/**
* Data of a paginated list of items with a token to fetch the next page.
*/
export interface TokenPaginationModelData<T> {
results: T[];
token?: string;
}

/**
* A paginated list of items with a token to fetch the next page. Contains a
* portion of the results of a query and a token that identifies the last item
* in the list, which can be used to get the next items.
*/
export class TokenPaginationModel<T> {
constructor(readonly data: TokenPaginationModelData<T>) {}
constructor(private readonly data: TokenPaginationModelData<T>) {}

/**
* The list of items in the current page.
*/
get results() {
return this.data.results;
}

/**
* The identifier of the last item in the `results` list. Used as a token to
* fetch the next page of items.
*/
get token() {
return this.data.token;
}

/**
* Serializes the paginated list
*
* @param serializer Function that converts an item in the `results` list to a serializable format.
* @returns A serialized version of the paginated list.
*/
toData<U>(serializer: (data: T) => U): TokenPaginationModelData<U> {
return {
...this.data,
results: this.results.map(serializer),
};
}

/**
* Deserializes the paginated list
*
* @param serializer Function that converts a serialized item in the `results` list to a domain model
* @returns The original paginated list deserialized.
*/
static fromData<T, U>(
data: TokenPaginationModelData<U>,
deserializer: (data: U) => T,
Expand Down
1 change: 1 addition & 0 deletions src/common/ui/components/form/checkbox-form-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export function CheckboxFormField({ name, label }: CheckboxFormFieldProps) {
label={label}
value={field.value}
onChange={field.onChange}
data-testid={name}
/>
</FormControl>
<FormMessage />
Expand Down
Loading