This example uses Zimic with Playwright in end-to-end tests.
The tested application is a simple Next.js project, fetching repositories from the GitHub API.
- Application:
src/app/page.tsx
- GitHub fetch:
src/services/github.ts
A postinstall
script in package.json
is used to install Playwright's browsers.
Note
Preventing racing conditions
The mocks are loaded before starting the application to prevent racing conditions in tests. This example uses a single
interceptor server, so we would need to reduce the number of workers to 1 if the mocks were applied inside the tests
or beforeEach
/beforeAll
/afterEach
/afterAll
hooks. That would make the tests significantly slower in large
applications, which is a trade-off to consider.
If using a single test worker is not a problem for your project, applying the mocks inside your tests or hooks is perfectly possible. On the other hand, if you need parallelism, you can still simulate dynamic behavior by creating all of the mocks you need beforehand in a load script like in this example. Using restrictions is a good way to narrow down the scope of those mocks.
An example test suite uses Playwright 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.
- GitHub interceptor and mocks:
tests/interceptors/github.ts
The script tests/interceptors/scripts/load.ts
loads the interceptors and mocks
before the application is started in development. It is used by the command dev:mock
in
package.json
.
- Test suite:
src/app/__tests__/HomePage.e2e.test.ts
- Playwright configuration:
playwright.config.ts
-
Clone this example:
mkdir zimic cd zimic git init git remote add origin [email protected]:zimicjs/zimic.git git sparse-checkout init git sparse-checkout set examples/with-playwright git pull origin v0 cd examples/with-playwright
-
Install the dependencies:
pnpm install
-
Run the tests:
-
Start the application:
pnpm run dev:mock
After started, it will be available at http://localhost:3004.
-
In another terminal, run the tests:
pnpm run test --ui
-