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

Introduce Cypress #84

Merged
merged 12 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from 11 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
41 changes: 41 additions & 0 deletions .github/workflows/e2e-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Next.js E2E Tests

on:
push:
branches:
- main
pull_request:
branches:
- main

jobs:
check:
name: E2E job with Cypress
runs-on: ubuntu-latest
env:
NEXT_PUBLIC_APP_URL: http://localhost:3000
UNILOGIN_SESSION_SECRET: XXX
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
ref: ${{ github.head_ref }}
fetch-depth: 0 # Required to retrieve git history

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"

- name: Install dependencies
run: yarn install --frozen-lockfile --no-progress --non-interactive

- name: Build the Nextjs app and run Cypress tests
uses: cypress-io/github-action@v4
with:
install: false
build: yarn build
start: yarn start
wait-on: http://localhost:3000
runTests: yarn cypress:run
browser: chrome
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ next-env.d.ts
# vscode
.vscode

# Cypress
cypress/videos
cypress/screenshots


*storybook.log

Expand Down
24 changes: 20 additions & 4 deletions README.md
JacobArrow marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ The application is now running at [https://localhost:3000](https://localhost:300
- [Tailwind CSS][tailwind]
- [ESLint][eslint] & [Prettier][prettier]
- [Storybook][storybook] & [Chromatic][chromatic]
- [cypress][cypress]
- [Vitest][vitest]

### Project structure
Expand Down Expand Up @@ -237,6 +238,17 @@ This will launch the Storybook server, and you can view the component library in

**_We create Storybook stories strictly on a "render component" basis. This means focusing on smaller atomic components that are not specific to generated code._**

### Cypress

Cypress is an end-to-end testing framework that allows us to write and run tests for the application's core user journeys.

To start Cypress, run the following commands:

```bash
yarn dev # Start the development server
yarn cypress:run # Run all Cypress tests
```

## Deployment

### git branches and pull requests
Expand Down Expand Up @@ -309,19 +321,22 @@ Quality assurance (QA) is a critical aspect of our development process, ensuring

1. **Automated Unit Testing**: Workflows like `unit-test.yml` run unit tests automatically, ensuring that individual components and utilities function correctly. This helps catch bugs early in the development process.

2. **Code Quality Checks**: Workflows such as `eslint-check.yml` and `prettier-check.yml` enforce coding standards and consistent formatting. This ensures that the codebase remains clean, readable, and maintainable.
2. **End-to-end Testing**: Workflows such as `e2e-test.yml` run end-to-end tests using Cypress to simulate user interactions and test the application's core user journeys. This helps ensure that the application and important features work as expected. This also helps catch bugs early in the development process.

3. **Code Quality Checks**: Workflows such as `eslint-check.yml` and `prettier-check.yml` enforce coding standards and consistent formatting. This ensures that the codebase remains clean, readable, and maintainable.

3. **Type Safety**: The `type-check.yml` workflow runs TypeScript checks to ensure type safety across the project. This helps prevent type-related errors and improves code reliability.
4. **Type Safety**: The `type-check.yml` workflow runs TypeScript checks to ensure type safety across the project. This helps prevent type-related errors and improves code reliability.

4. **Accessibility Testing**: The `accessibility-test.yml` workflow runs accessibility tests on each [Storybook] Story using [Axe] through [Playwright]. This ensures that the application meets accessibility standards and provides a better user experience for all users.
5. **Accessibility Testing**: The `accessibility-test.yml` workflow runs accessibility tests on each [Storybook] Story using [Axe] through [Playwright]. This ensures that the application meets accessibility standards and provides a better user experience for all users.

5. **Visual Regression Testing**: The `chromatic.yml` workflow runs Chromatic to visualize and test UI components in [Storybook]. This helps catch visual regressions and ensures that UI changes do not introduce unexpected issues.
6. **Visual Regression Testing**: The `chromatic.yml` workflow runs Chromatic to visualize and test UI components in [Storybook]. This helps catch visual regressions and ensures that UI changes do not introduce unexpected issues.

## Developers

- Adam Antal - [email protected]
- Mikkel Jakobsen - [email protected]
- Thomas Gross Rasmussen - [email protected]
- Jacob Pihl - [email protected]

[nextjs]: https://nextjs.org/
[app-router]: https://nextjs.org/docs/app
Expand All @@ -339,4 +354,5 @@ Quality assurance (QA) is a critical aspect of our development process, ensuring
[vitest]: https://vitest.dev/
[axe]: https://playwright.dev/docs/accessibility-testing
[playwright]: https://playwright.dev/
[cypress]: https://www.cypress.io/
[dpl-cms]: https://github.com/danskernesdigitalebibliotek/dpl-cms
2 changes: 2 additions & 0 deletions app/auth/callback/unilogin/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,5 @@ export async function GET(request: NextRequest) {
headers,
})
}

export const dynamic = "force-dynamic"
4 changes: 0 additions & 4 deletions app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import VideoPlayer from "@/components/videoPlayer/VideoPlayer"
import goConfig from "@/lib/config/goConfig"

const wellknownUrl = goConfig("service.unilogin.wellknown.url")
export default async function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center gap-16 p-8 pb-20 sm:p-20">
<main className="row-start-2 flex flex-col items-center gap-8 sm:items-start">
<pre>Wellknown url: {wellknownUrl}</pre>

<VideoPlayer />
</main>
</div>
Expand Down
7 changes: 4 additions & 3 deletions components/global/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@ import DarkModeToggle from "@/components/shared/darkModeToggle/DarkModeToggle"
import Icon from "@/components/shared/icon/Icon"
import SearchInput from "@/components/shared/searchInput/SearchInput"
import SmartLink from "@/components/shared/smartLink/SmartLink"
import { cyKeys } from "@/cypress/support/constants"

import ProfileButton from "./ProfileButton"

function Header() {
return (
<div>
<header>
<div className="flex h-navigation-top-height items-center justify-center bg-background-overlay">
<p className="text-typo-caption">Biblioterernes ebøger og lydbøger</p>
</div>
<div className="content-container grid h-navigation-height grid-cols-3 items-center">
<div className="flex-0 flex items-center">
<div className="flex-0 flex items-center" data-cy={cyKeys["go-logo"]}>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't figure out what I think about adding code to elements that only have relevance for Cypress. I know its a common practice but still worth mentioning?

I would like our components to be as clean as possible, preferably without extra data attributes.

If we keep it, I think either data-cy={cyKeys["go-logo"]} should be placed on Button or Icon"

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is the best practice for selecting elements with Cypress and I think we should stick with that :)
https://docs.cypress.io/app/core-concepts/best-practices#Selecting-Elements

It also allows to typecheck our element selectors, which is always nice.

Regarding where it is placed; it doesnt matter in this PR, as it is only for demonstrating the usage.
frontpage.cy.ts will be updated once we actually have some content to test.

<Button ariaLabel="Gå til forsiden" asChild className="inline-flex px-3">
<SmartLink href="/" className="inline-flex">
<Icon name="logo-borderless" />
Expand Down Expand Up @@ -43,7 +44,7 @@ function Header() {
</div>
</div>
</div>
</div>
</header>
)
}

Expand Down
11 changes: 11 additions & 0 deletions cypress.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from "cypress"

export default defineConfig({
e2e: {
baseUrl: "http://localhost:3000",
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
})
9 changes: 9 additions & 0 deletions cypress/e2e/frontpage.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
describe("Front Page Tests", () => {
it("Should include a header and a footer", () => {
cy.visit("/")

cy.get("header").should("exist")
cy.get("footer").should("exist")
cy.dataCy("go-logo").should("exist")
})
})
14 changes: 14 additions & 0 deletions cypress/support/commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable @typescript-eslint/no-namespace */
import { CyKey } from "./constants"

declare global {
namespace Cypress {
interface Chainable {
dataCy(value: CyKey): Chainable<JQuery<HTMLElement>>
}
}
}

Cypress.Commands.add("dataCy", selector => {
return cy.get(`[data-cy="${selector}"]`)
})
5 changes: 5 additions & 0 deletions cypress/support/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const cyKeys = {
"go-logo": "go-logo",
} as const

export type CyKey = keyof typeof cyKeys
1 change: 1 addition & 0 deletions cypress/support/e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
import "./commands"
27 changes: 13 additions & 14 deletions lib/session/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,20 @@ export async function getSession(options?: {
request: NextRequest
response: NextResponse
}): Promise<IronSession<TSessionData>> {
const session = !options
? await getIronSession<TSessionData>(await cookies(), sessionOptions)
: await getIronSession<TSessionData>(options.request, options.response, sessionOptions)
if (!session.isLoggedIn) {
session.isLoggedIn = false
session.access_token = defaultSession.access_token
session.refresh_token = defaultSession.refresh_token
session.id_token = defaultSession.id_token
session.expires = defaultSession.expires
session.refresh_expires = defaultSession.refresh_expires
session.userInfo = defaultSession.userInfo
session.type = defaultSession.type
try {
const session = !options
? await getIronSession<TSessionData>(await cookies(), sessionOptions)
: await getIronSession<TSessionData>(options.request, options.response, sessionOptions)

if (!session?.isLoggedIn) {
Object.assign(session, defaultSession)
}

return session
} catch (error) {
console.error(error)
return defaultSession as IronSession<TSessionData>
}

return session
}

export const setTokensOnSession = async (
Expand Down
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
"test:accessibility": "test-storybook",
"test:unit:once": "vitest run",
"test:unit": "vitest",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"cypress:open": "cypress open",
"cypress:run": "cypress run"
},
"dependencies": {
"@next/env": "15.0.3",
Expand Down Expand Up @@ -86,6 +88,7 @@
"@types/react-dom": "npm:[email protected]",
"@vitejs/plugin-react": "^4.3.2",
"axe-playwright": "^2.0.3",
"cypress": "^13.16.1",
"eslint": "^8.0.0",
"eslint-config-next": "15.0.3",
"eslint-config-prettier": "^9.1.0",
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "cypress"],
"exclude": [
"node_modules",
"lib/rest/cover-service-api/model",
Expand Down
Loading
Loading