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

docs(examples): next.js app and pages router (#163) #167

Merged
merged 5 commits into from
May 25, 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
3 changes: 2 additions & 1 deletion .commitlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
"examples-jest-node",
"examples-jest-jsdom",
"examples-playwright",
"examples-next-js"
"examples-next-js-app",
"examples-next-js-pages"
]
],
"scope-empty": [2, "never"]
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,4 @@ jobs:
--filter !zimic \
--filter !@zimic/* \
$([[ '${{ matrix.typescript-version }}' =~ ^(4\.|5\.0) ]] && \
echo '--filter !zimic-example-with-playwright --filter !zimic-example-with-next-js')
echo '--filter !zimic-example-with-playwright --filter !zimic-example-with-next-js-app --filter !zimic-example-with-next-js-pages')
3 changes: 2 additions & 1 deletion examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@

## Next.js

- [With Next.js](./with-next-js)
- [With Next.js App Router](./with-next-js-app)
- [With Next.js Pages Router](./with-next-js-pages)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
NODE_ENV=test
NODE_ENV=development

ZIMIC_SERVER_URL=http://localhost:3005
NEXT_PUBLIC_GITHUB_API_BASE_URL=$ZIMIC_SERVER_URL/github
1 change: 1 addition & 0 deletions examples/with-next-js-app/.env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NODE_ENV=test
32 changes: 32 additions & 0 deletions examples/with-next-js-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Dependencies
/node_modules

# Testing
/tests/outputs
/tests/reports

# Next.js
/.next
/out

# Production
/build

# Misc
.DS_Store
*.pem

# Debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Local env files
.env*.local

# Vercel
.vercel

# TypeScript
*.tsbuildinfo
next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
<h1>
Zimic + Next.js
Zimic + Next.js App Router
</h2>

This example uses Zimic with [Next.js](https://nextjs.org). The application is verified with end-to-end tests using
[Playwright](https://playwright.dev).

## Application

The application is a simple [Next.js](https://nextjs.org) application, using both the
[App Router](https://nextjs.org/docs/app) and the [Pages Router](https://nextjs.org/docs/pages). It fetches repositories
from the [GitHub API](https://docs.github.com/en/rest).
The application is a simple [Next.js](https://nextjs.org) application using the
[App Router](https://nextjs.org/docs/app). It fetches repositories from the
[GitHub API](https://docs.github.com/en/rest).

- Application:
- App Router version: [`src/app/app/page.page.tsx`](./src/app/app/page.page.tsx)
- Pages Router version: [`src/pages/pages.page.tsx`](./src/pages/pages.page.tsx)
- Application: [`src/app/app/page.page.tsx`](./src/app/page.tsx)
- Interceptor provider:
[`src/providers/interceptors/InterceptorProvider.tsx`](./src/providers/interceptors/InterceptorProvider.tsx)
- This provider is used to apply Zimic mocks when the application is started in development.
- GitHub fetch: [`src/services/github.ts`](./src/services/github.ts)
- Before fetching resources, it is necessary to wait for the interceptors and fixtures to be loaded. This is done via
`await waitForLoadedInterceptors();`.

A `postinstall` in [`package.json`](./package.json#L11) script is used to install Playwright's browsers.
A `postinstall` in [`package.json`](./package.json) script is used to install Playwright's browsers.

## Testing

Expand All @@ -48,9 +46,9 @@ GitHub API and simulate a test case where the repository is found and another wh
git init
git remote add origin git@github.com:diego-aquino/zimic.git
git sparse-checkout init
git sparse-checkout set examples/with-next-js
git sparse-checkout set examples/with-next-js-app
git pull origin main
cd examples/with-next-js
cd examples/with-next-js-app
```

2. Install the dependencies:
Expand All @@ -67,8 +65,7 @@ GitHub API and simulate a test case where the repository is found and another wh
pnpm run dev
```

After started, the App Router version will be available at [http://localhost:3004/app](http://localhost:3004/app)
and the Pages Router version at [http://localhost:3004/pages](http://localhost:3004/pages).
After started, the application will be available at [http://localhost:3004](http://localhost:3004).

2. In another terminal, run the tests:

Expand Down
4 changes: 4 additions & 0 deletions examples/with-next-js-app/next.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "zimic-example-with-next-js",
"name": "zimic-example-with-next-js-app",
"version": "0.0.0",
"private": false,
"scripts": {
"dev": "dotenv -c development -- zimic server start --port 3005 --ephemeral -- next dev --port 3004",
"dev": "dotenv -c development -- zimic server start --port 3005 --ephemeral -- next dev --turbo --port 3004",
"test": "dotenv -c test -- dotenv -c development -- playwright test",
"test:turbo": "pnpm run test",
"types:check": "tsc --noEmit",
Expand Down
53 changes: 53 additions & 0 deletions examples/with-next-js-app/src/__tests__/HomePage.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import test, { expect } from '@playwright/test';

import { githubFixtures } from '../../tests/interceptors/github/fixtures';

test.describe('Home page', () => {
const { repository } = githubFixtures;

test.beforeEach(async ({ page }) => {
await page.goto('/');
});

test('should render a GitHub repository, if found', async ({ page }) => {
const ownerInput = page.getByRole('textbox', { name: 'Owner' });
await expect(ownerInput).toBeVisible();
await ownerInput.fill(repository.owner.login);

const repositoryInput = page.getByRole('textbox', { name: 'Repository' });
await expect(repositoryInput).toBeVisible();
await repositoryInput.fill(repository.name);

const submitButton = page.getByRole('button', { name: 'Search' });
await expect(submitButton).toBeVisible();
await submitButton.click();

await expect(page).toHaveURL(`/?owner=${repository.owner.login}&repo=${repository.name}`);

const repositoryLink = page.getByRole('link', { name: repository.full_name });
await expect(repositoryLink).toBeVisible();
await expect(repositoryLink).toHaveAttribute('href', repository.html_url);
await expect(repositoryLink).toHaveAttribute('target', '_blank');
await expect(repositoryLink).toHaveAttribute('rel', 'noopener noreferrer');
});

test('should render a message if the GitHub repository is not found', async ({ page }) => {
const ownerInput = page.getByRole('textbox', { name: 'Owner' });
await expect(ownerInput).toBeVisible();
await ownerInput.fill('unknown');

const repositoryInput = page.getByRole('textbox', { name: 'Repository' });
await expect(repositoryInput).toBeVisible();
await repositoryInput.fill('unknown');

const submitButton = page.getByRole('button', { name: 'Search' });
await expect(submitButton).toBeVisible();
await submitButton.click();

await expect(page).toHaveURL('/?owner=unknown&repo=unknown');

const notFoundMessage = page.getByRole('status');
await expect(notFoundMessage).toBeVisible();
await expect(notFoundMessage).toHaveText('Repository not found.');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export interface HomePageSearchParams {

function useHomePageSearchParams() {
const router = useRouter();
const searchParams = useSearchParams()!; // eslint-disable-line @typescript-eslint/no-non-null-assertion
const searchParams = useSearchParams();

const ownerName = searchParams.get('owner' satisfies keyof HomePageSearchParams);
const repositoryName = searchParams.get('repo' satisfies keyof HomePageSearchParams);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { Metadata } from 'next';
import { Inter } from 'next/font/google';
import { PropsWithChildren } from 'react';

import { loadInterceptors } from '../../../tests/interceptors';
import InterceptorProvider from '../../providers/interceptors/InterceptorProvider';
import { loadInterceptors } from '../../tests/interceptors';
import InterceptorProvider from '../providers/interceptors/InterceptorProvider';

import '../../styles/global.css';
import '../styles/global.css';

const inter = Inter({ subsets: ['latin'] });

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { Suspense } from 'react';

import GitHubRepositoryForm from '../components/GitHubRepositoryForm';
import GitHubRepositoryShowcase from '../components/GitHubRepositoryShowcase';
import { HomePageSearchParams } from '../hooks/useHomePageSearchParams';
import GitHubRepositoryForm from './components/GitHubRepositoryForm';
import GitHubRepositoryShowcase from './components/GitHubRepositoryShowcase';
import { HomePageSearchParams } from './hooks/useHomePageSearchParams';

interface Props {
searchParams: HomePageSearchParams;
Expand Down
11 changes: 11 additions & 0 deletions examples/with-next-js-app/tailwind.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Config } from 'tailwindcss';

const config: Config = {
content: ['./src/app/**/*.{ts,tsx}', './src/components/**/*.{ts,tsx}'],
theme: {
extend: {},
},
plugins: [],
};

export default config;
3 changes: 3 additions & 0 deletions examples/with-next-js-pages/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
NODE_ENV=development

NEXT_PUBLIC_GITHUB_API_BASE_URL=https://api.github.com
1 change: 1 addition & 0 deletions examples/with-next-js-pages/.env.test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
NODE_ENV=test
76 changes: 76 additions & 0 deletions examples/with-next-js-pages/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<h1>
Zimic + Next.js Pages Router
</h2>

This example uses Zimic with [Next.js](https://nextjs.org). The application is verified with end-to-end tests using
[Playwright](https://playwright.dev).

## Application

The application is a simple [Next.js](https://nextjs.org) application using the
[Pages Router](https://nextjs.org/docs/pages). It fetches repositories from the
[GitHub API](https://docs.github.com/en/rest).

- Application: [`src/pages/index.page.tsx`](./src/pages/index.page.tsx)
- Interceptor provider:
[`src/providers/interceptors/InterceptorProvider.tsx`](./src/providers/interceptors/InterceptorProvider.tsx)
- This provider is used to apply Zimic mocks when the application is started in development.
- GitHub fetch: [`src/services/github.ts`](./src/services/github.ts)
- Before fetching resources, it is necessary to wait for the interceptors and fixtures to be loaded. This is done via
`await waitForLoadedInterceptors();`.

A `postinstall` in [`package.json`](./package.json) script is used to install Playwright's browsers and initialize
Zimic's mock service worker to the `./public` directory. The mock service worker at `./public/mockServiceWorker.js` is
ignored in the [`.gitignore`](./.gitignore) file.

## Testing

An example test suite uses [Playwright](https://playwright.dev) to test the application. Zimic is used to mock the
GitHub API and simulate a test case where the repository is found and another where it is not.

### Zimic

- GitHub interceptor: [`tests/interceptors/github/interceptor.ts`](./tests/interceptors/github/interceptor.ts)
- Fixtures: [`tests/interceptors/github/fixtures.ts`](./tests/interceptors/github/fixtures.ts)

### Test

- Test suite: [`src/__tests__/HomePage.e2e.test.ts`](./src/__tests__/HomePage.e2e.test.ts)
- Playwright configuration: [`playwright.config.ts`](./playwright.config.ts)

### Running

1. Clone this example:

```bash
mkdir zimic
cd zimic
git init
git remote add origin git@github.com:diego-aquino/zimic.git
git sparse-checkout init
git sparse-checkout set examples/with-next-js-pages
git pull origin main
cd examples/with-next-js-pages
```

2. Install the dependencies:

```bash
pnpm install
```

3. Run the tests:

1. Start the application:

```bash
pnpm run dev
```

After started, the application will be available at [http://localhost:3006](http://localhost:3006).

2. In another terminal, run the tests:

```bash
pnpm run test --ui
```
31 changes: 31 additions & 0 deletions examples/with-next-js-pages/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "zimic-example-with-next-js-pages",
"version": "0.0.0",
"private": false,
"scripts": {
"dev": "dotenv -c development -- next dev --turbo --port 3006",
"test": "dotenv -c test -- dotenv -c development -- playwright test",
"test:turbo": "pnpm run test",
"types:check": "tsc --noEmit",
"deps:install-playwright": "pnpm playwright install chromium",
"postinstall": "pnpm deps:install-playwright && zimic browser init ./public || echo 'Could not postinstall.'"
},
"dependencies": {
"@tanstack/react-query": "^5.36.2",
"clsx": "^2.1.1",
"dotenv-cli": "^7.3.0",
"next": "14.2.3",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@playwright/test": "^1.44.0",
"@types/node": "^20.11.30",
"@types/react": "^18.3.2",
"@types/react-dom": "^18.3.0",
"postcss": "^8.4.38",
"tailwindcss": "^3.4.1",
"typescript": "^5.4.3",
"zimic": "latest"
}
}
43 changes: 43 additions & 0 deletions examples/with-next-js-pages/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
testDir: './src',
testMatch: '**/__tests__/**/*.e2e.test.ts',
fullyParallel: true,
retries: 1,
reporter: [['html', { outputFolder: './tests/reports' }]],
outputDir: './tests/outputs',

expect: {
timeout: 10 * 1000,
},

use: {
baseURL: 'http://localhost:3006',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'on-first-retry',
actionTimeout: 10 * 1000,
navigationTimeout: 30 * 1000,
},

projects: [
{
name: 'chromium-desktop',
use: {
...devices['Desktop Chrome'],
isMobile: false,
defaultBrowserType: 'chromium',
},
},
],

webServer: {
command: 'pnpm run dev',
port: 3006,
stdout: 'pipe',
stderr: 'pipe',
reuseExistingServer: true,
timeout: 30 * 1000,
},
});
Loading
Loading