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

Setup end-2-end tests #30

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,4 @@ yarn-error.log*

.git/
.yarn/
.history/
26 changes: 26 additions & 0 deletions .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Playwright Tests
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
test:
timeout-minutes: 60
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: "14.x"
- name: Install dependencies
run: yarn
- name: Install Playwright
run: npx playwright install --with-deps
- name: Run Playwright tests
run: yarn playwright test
- uses: actions/upload-artifact@v2
if: always()
with:
name: playwright-test-results
path: test-results/
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ tsconfig.tsbuildinfo
npm-debug.log*
yarn-debug.log*
yarn-error.log*
test-results/
playwright-report/
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,20 @@ yarn dev

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

## Test

Run end-2-end tests with [Playwright](https://playwright.dev/).

```sh
yarn test
```

Run tests in interactive debug mode.

```sh
yarn test:debug
```

## Environment variables

All secrets should never be committed to the git repo, but saved in the environment variables.
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
"lint:tsc": "tsc --project .",
"lint:yarn-dedupe": "yarn dedupe --check",
"start": "next start",
"postinstall": "husky install"
"postinstall": "husky install",
"test": "yarn playwright test --project=chromium",
"test:debug": "PWDEBUG=1 yarn test login"
},
"lint-staged": {
"**/*": [
Expand All @@ -29,6 +31,7 @@
"@auth0/nextjs-auth0": "^1.6.2",
"@prisma/client": "^3.8.1",
"dayjs": "^1.10.7",
"dotenv": "^14.2.0",
"next": "^12.0.7",
"react": "^17.0.2",
"react-dom": "^17.0.2",
Expand All @@ -41,6 +44,7 @@
"@kachkaev/markdownlint-config": "^0.3.0",
"@netlify/plugin-nextjs": "^4.1.1",
"@next/eslint-plugin-next": "^12.0.7",
"@playwright/test": "^1.18.0",
"@types/node": "^16.11.19",
"@types/react": "^17.0.38",
"@types/react-gravatar": "^2.6.10",
Expand Down
112 changes: 112 additions & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { devices, PlaywrightTestConfig } from "@playwright/test";

/**
* See https://playwright.dev/docs/test-configuration.
*/
const config: PlaywrightTestConfig = {
testDir: "./tests",

/* Reuse auth state */
globalSetup: "./tests/global-setup",

/* Maximum time one test can run for. */
timeout: 30 * 1000,

expect: {
/**
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000,
},

/* Fail the build on CI if you accidentally left test.only in the source code. */
forbidOnly: !!process.env.CI,

/* Retry on CI only */
retries: process.env.CI ? 2 : 0,

/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,

/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: "html",

/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
actionTimeout: 0,

/* Base URL to use in actions like `await page.goto('/')`. */
// baseURL: 'http://localhost:3000',

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: "on-first-retry",
},

/* Configure projects for major browsers */
projects: [
{
name: "chromium",

/* Project-specific settings. */
use: {
...devices["Desktop Chrome"],
},
},

{
name: "firefox",
use: {
...devices["Desktop Firefox"],
},
},

{
name: "webkit",
use: {
...devices["Desktop Safari"],
},
},

/* Test against mobile viewports. */
// {
// name: 'Mobile Chrome',
// use: {
// ...devices['Pixel 5'],
// },
// },
// {
// name: 'Mobile Safari',
// use: {
// ...devices['iPhone 12'],
// },
// },

/* Test against branded browsers. */
// {
// name: 'Microsoft Edge',
// use: {
// channel: 'msedge',
// },
// },
// {
// name: 'Google Chrome',
// use: {
// channel: 'chrome',
// },
// },
],

/* Folder for test artifacts such as screenshots, videos, traces, etc. */
// outputDir: 'test-results/',

/* Run your local dev server before starting the tests */
// webServer: {
// command: 'npm run start',
// port: 3000,
// },
};

// eslint-disable-next-line import/no-default-export
export default config;
1 change: 1 addition & 0 deletions tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
state.json
34 changes: 34 additions & 0 deletions tests/comments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { expect, test } from "@playwright/test";

import { mockLoginWithEmail, testAuthData } from "./helpers/auth-helpers";
import { TestParams } from "./helpers/types";

// eslint-disable-next-line jest/no-done-callback
test("add comment", async ({ page }: TestParams) => {
await mockLoginWithEmail({ page });

const newCommentText = "Hi, this is my comment";

// Go to /
await page.goto(testAuthData.URL);
// Click text=Comments
await Promise.all([
page.waitForNavigation(/* { url: '/iframes/comments/1' } */),
page.click("text=Comments"),
]);
// Click textarea
await page.click("textarea");
// Fill textarea
await page.fill("textarea", newCommentText);
// Press Enter
await page.press("textarea", "Enter");
// Click text=Отправить
await page.click("text=Отправить");

await expect(page.locator(`text=${newCommentText}`)).toHaveText(
newCommentText,
);
await expect(page.locator(`text=${testAuthData.LOGIN}`)).toHaveText(
testAuthData.LOGIN,
);
});
8 changes: 8 additions & 0 deletions tests/global-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import dotenv from "dotenv";

dotenv.config({ path: ".env.local" });

const globalSetup = () => {};

// eslint-disable-next-line import/no-default-export
export default globalSetup;
89 changes: 89 additions & 0 deletions tests/helpers/auth-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import dotenv from "dotenv";

import { TestParams } from "./types";

dotenv.config({ path: ".env.local" });

export const testAuthData = {
URL: process.env.AUTH0_BASE_URL as string,
LOGIN: process.env.TEST_LOGIN as string,
PASSWORD: process.env.TEST_PASSWORD as string,
authMeResp: {
nickname: "dtp.stat.test",
name: "[email protected]",
picture: "",
// eslint-disable-next-line @typescript-eslint/naming-convention
updated_at: "2022-01-21T23:42:43.606Z",
sub: "auth0|61eb2c2059e0a90071d8f69f",
},
};

export const loginWithEmail = async ({ page }: TestParams) => {
// Go to /
await page.goto(testAuthData.URL);

// Click text=Login
await Promise.all([
page.waitForNavigation(/* { url: 'https://dev-9pt5c6ik.us.auth0.com/u/login?state=hKFo2SBSXy14NTExZ1M3RWJobTFCU1hHS2xzS0FZbkpMejJRVqFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIHk3d2tZVjZwbnI3SzB1UHowUkdCZjItWWpjaExyNnd6o2NpZNkgVklNTGgwNFNLdjhxUjdXc2VwRUhNT3FrdGJSQlNVeTE' } */),
page.click("text=Login"),
]);

// Fill input[name="username"]
await page.fill('input[name="username"]', testAuthData.LOGIN);

// Click input[name="password"]
await page.click('input[name="password"]');

// Fill input[name="password"]
await page.fill('input[name="password"]', testAuthData.PASSWORD);

// Click button:has-text("Continue")
await Promise.all([
page.waitForNavigation(/* { url: 'http://localhost:3000/' } */),
page.click('button:has-text("Continue")'),
]);
};

export const loginWithGoogle = async ({ page }: TestParams) => {
// Go to /
await page.goto(testAuthData.URL);

// Click text=Login
await Promise.all([
page.waitForNavigation(/* { url: 'https://dev-9pt5c6ik.us.auth0.com/u/login?state=hKFo2SB1OGdCaDdaSUMtQlU0X2NlQWcyTUdrZk5ZU2tXeHdMMKFur3VuaXZlcnNhbC1sb2dpbqN0aWTZIGduLW8xY2pKTFFoQkpuS2dXaEhRRGh6UjAwMmxLTk9mo2NpZNkgVklNTGgwNFNLdjhxUjdXc2VwRUhNT3FrdGJSQlNVeTE' } */),
page.click("text=Login"),
]);
// Click button:has-text("Continue with Google")
await Promise.all([
page.waitForNavigation(/* { url: 'https://accounts.google.com/o/oauth2/auth/identifier?login_hint&response_type=code&redirect_uri=https%3A%2F%2Flogin.us.auth0.com%2Flogin%2Fcallback&scope=email%20profile&state=n8xYkwcxbRy0TbhioEowcLaDwAoKBhUm&client_id=104565000066-q7q63bouq2ct8gj73drmpu186amn6a3f.apps.googleusercontent.com&flowName=GeneralOAuthFlow' } */),
page.click('button:has-text("Continue with Google")'),
]);
// Fill [aria-label="Телефон\ или\ адрес\ эл\.\ почты"]
await page.fill(
'[aria-label="Телефон\\ или\\ адрес\\ эл\\.\\ почты"]',
testAuthData.LOGIN,
);
// Click button:has-text("Далее")
await Promise.all([
page.waitForNavigation(/* { url: 'https://accounts.google.com/signin/v2/challenge/pwd?login_hint&response_type=code&redirect_uri=https%3A%2F%2Flogin.us.auth0.com%2Flogin%2Fcallback&scope=email%20profile&state=n8xYkwcxbRy0TbhioEowcLaDwAoKBhUm&client_id=104565000066-q7q63bouq2ct8gj73drmpu186amn6a3f.apps.googleusercontent.com&flowName=GeneralOAuthFlow&cid=1&navigationDirection=forward&TL=AM3QAYZq7nx8YKprItrlvoTViq5YZC2HEuc1NeRa2BVV0ZsxYWQqJ4cxbB74WWE8' } */),
page.click('button:has-text("Далее")'),
]);
// Fill [aria-label="Введите\ пароль"]
await page.fill('[aria-label="Введите\\ пароль"]', testAuthData.PASSWORD);
// Click button:has-text("Далее")
await Promise.all([
page.waitForNavigation(/* { url: 'http://localhost:3000/' } */),
page.click('button:has-text("Далее")'),
]);
};

export const mockAuth0Login = async ({ page }: TestParams) => {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
await page.route(`${testAuthData.URL}/api/auth/me`, (route) =>
route.fulfill({ body: JSON.stringify(testAuthData.authMeResp) }),
);
};

export const mockLoginWithEmail = async ({ page }: TestParams) => {
await mockAuth0Login({ page });
};
5 changes: 5 additions & 0 deletions tests/helpers/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Page } from "@playwright/test";

export interface TestParams {
page: Page;
}
43 changes: 43 additions & 0 deletions tests/login.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { chromium, expect, test } from "@playwright/test";

import { loginWithEmail, testAuthData } from "./helpers/auth-helpers";

test("login with email", async () => {
// Create a Chromium browser instance
const browser = await chromium.launch();
const context = await browser.newContext({
locale: "ru-RU",
});
const page = await context.newPage();

await loginWithEmail({ page });

// Save storage state into the file.
await context.storageState({ path: "tests/state.json" });

// Go to /
await page.goto(testAuthData.URL);

const header = page.locator("h4");

// Confirm logged in user
await expect(header).toHaveText(testAuthData.LOGIN);
});

test("load auth0 session", async () => {
// Create a Chromium browser instance
const browser = await chromium.launch();
const context = await browser.newContext({
locale: "ru-RU",
storageState: "tests/state.json",
});
const page = await context.newPage(); // Create a new context with the saved storage state.

// Go to /
await page.goto(testAuthData.URL);

const header = page.locator("h4");

// Confirm logged in user
await expect(header).toHaveText(testAuthData.LOGIN);
});
Loading