Simulated environment

An environment to simulate an actual real-world scenario.

Well, before proceeding to the users tests, let's have a test database in order to test the CRUD operations. An actual Postgres database will be used so that the tests are closer to a real-world scenario. Environment variables will also be used for better organization.

We can then go to the .env file and perform the following steps:

  • Copy all the variables that start with DATASOURCE and prefix them with TEST_

  • Also adjust the variables being used in the TEST_DATASOURCE_URL

  • Set the TEST_DATASOURCE_PORT to 5433, as to prevent a collision with the other database

Remember to adjust the .env.example file accordingly.

Once again in the docker-compose.yml file, insert the data for the test database:

test-database:
  image: postgres
  restart: always
  ports:
    - ${TEST_DATASOURCE_PORT}:5432
  environment:
    POSTGRES_PASSWORD: ${TEST_DATASOURCE_PASSWORD}

And in the file package.json, let's add a pre and post scripts for test:e2e around it. They will be responsible for, respectively, creating and excluding the test database.

"pretest:e2e": "docker-compose up -d test-database",
"posttest:e2e": "docker-compose stop test-database && docker-compose rm -f test-database",

If the tests fail, the test database will need to be deleted manually with the post script.

Inside the src folder, we can then create a configuration namespace for the test database in testing -> config -> test-database.config.

export default registerAs('testDatabase', () => {
  const config = {
    type: 'postgres',
    url: process.env.TEST_DATASOURCE_URL,
    autoLoadEntities: true,
    synchronize: true,
  } as const satisfies TypeOrmModuleOptions;
  return config;
});

Here, we turn on synchronize to automatically execute the migrations.

And we can create the file testing -> util -> testing.constants with the validation schema for the testing environment variables.

export const TEST_ENV_VALIDATION_SCHEMA = Joi.object({
  TEST_DATASOURCE_USERNAME: Joi.required(),
  TEST_DATASOURCE_PASSWORD: Joi.required(),
  TEST_DATASOURCE_HOST: Joi.required(),
  TEST_DATASOURCE_PORT: Joi.number().integer().positive().required(),
  TEST_DATASOURCE_DATABASE: Joi.required(),
  TEST_DATASOURCE_URL: Joi.required(),
});

We may then proceed to the actual tests.

Last updated