This project is a template demonstrating the usage of TestContainers with Next.js and Playwright in a very basic Todo-app. Uses Prisma as ORM and PostgreSQL as database.
- Next.js development environment with TestContainers
- Playwright tests with TestContainers
- Commands to take snapshots of PostgreSQL-database and being able to reset them
First, run the development server:
yarn devThis will start both the Next.js development server and the PostgreSQL-database in a TestContainer.
ctrl + cto stop the development serverctrl + dto stop the development server and remove the PostgreSQL-database containerctrl + sto take a snapshot of the PostgreSQL-databasectrl + rto reset the PostgreSQL-database to the last snapshot
To run the tests, run:
yarn e2eThis will start the PostgreSQL-database in a TestContainer and run the Playwright tests.
We have wrapped the next dev command for development and testing. This is to ensure that the TestContainers follows the lifecycle of the Next.js development server. In other words, both start and stop at the same time.
This also enables us to add commands to take snapshots of the PostgreSQL-database and reset it to the last snapshot.
Another important reason for wrapping the next dev command is to override the environment variables. This is necessary since we want to use a different database for testing than for development.
src/- Contains the Next.js application, a basic and boring Todo-app.prisma/- Contains the Prisma schema and database migrationstestcontainers/psql.ts- A module with functions to start and migrate (with Prisma) the PostgreSQL-database in a TestContainer, as well as taking snapshots and resetting the database.dev-server.ts- Wraps thenext devcommand for development. Also starts and migrates the PostgreSQL-database in a TestContainer. Also contains commands to take snapshots of the database and reset it..env.development- Environment variables for development.env.e2e- Environment variables for testingtests/e2e-dev-server.ts- Wraps thenext devcommand for testing. Does not start the PostgreSQL-database in a TestContainer, since we want Playwright to handle its lifecycle.tests/app-fixture.ts- Sets up a test fixture for Playwright to use. Starts and migrates the PostgreSQL-database in a TestContainer. Resets the database after each test.tests/todos.spec.ts- Playwright tests for the Todo-appconfig.ts- Loads configuration based on the environment, used by the dev/test servers.
Presented at BartJS Meetup on 27th of February 2025.
Slides from the talk available in the TestContainers-Talk-Slides.pdf file.