In this approach, we won’t use any tools that run the database in memory, then we will create a docker-compose file that specifies
this database configuration.
This is the basic docker-compose file to create a simple PostgreSQL container, with the follow credentials:
PORT: The port that performs Docker fowarding is 5433.
POSTGRES_USER: The PostgreSQL user name is application-tests (You can change, if you want).
POSTGRES_PASSWORD: The PostgreSQL user password is application-tests-admin (You can change, if you want).
After creating this file, you can run the follow command to create the container:
This container will be used mainly for you to be able to run your tests locally, in addition to serving as a basis for the
PostgreSQL configuration that will be created within our CI/CD container.
Configuring the Vitest
To configure Vitest, define PostgreSQL’s environment variables in your setup file like this:
This will ensure that all tests that use the database will point to your test database.
Configuring the Github Actions to run PostgreSQL
1. Creating a script to apply migrations
First of all, it is necessary to create a script that will always apply the necessary migrations within the GitHub Actions container running our tests. Since the container will terminate after all the tests are run, the script ensures the migrations are applied correctly.
You can use the following script, which will be executed with tsx within action:
2. Creating Github Action configuration
This configuration ensures that your test environment is set up consistently and automatically each time your tests run.
Conclusion
This blog post presents how to create a container for reproducible tests, configure your Vitest with several environments that point to this
container and a modern Github Action to try in CI/CD using everything presented.