Create an E2E Test

Learn how to implement an E2E test suite for UserController.

Implement an E2E test for UserController

Now that we have a basic understanding of the E2E testing concepts, it’s time to implement a real test in our app. In this lesson, we’ll explore the essential steps to configure a test database for E2E testing using DBSeedingService. We’ll cover configuring and seeding a test database dedicated to the E2E tests, allowing us to run tests against a controlled environment. Additionally, we’ll implement tests for the CRUD endpoints in UserController.

Configure test database

To set up a dedicated database, we need to create the database using the following SQL script. Note that the database is already provisioned in the live code editor. Therefore, the script is for reference.

CREATE Database AddressBookE2E;
Script to create a database for the E2E tests

Next, we can add a new .env.e2e environment file to configure the database connection for the E2E tests. Please note that we set the name of the database to be AddressBookE2E to utilize the newly created test database.

Press + to interact
DATABASE_HOST=localhost
DATATBASE_PORT=3306
DATABASE_USER=appuser
DATABASE_PASSWORD=password
DATABASE_NAME=AddressBookE2E
SYNCHRONIZE=true
JWT_SECRET_KEY=secretkey

If we run the tests, the connection to the test database will be initialized, and all tests will be run against the test database.

The DBSeedingService service

Then, we need to create a service to seed the database with predefined data before running tests. This ensures a consistent and controlled environment for the E2E testing.

To start, we store the test data in test-data.ts as constants.

Press + to interact
// test-data.ts
export class TestData {
static readonly user1 ={id: 1, user_name: 'user1', email: 'user1@example.com', password: 'password' };
static readonly expected_user1 ={id: 1, user_name: 'user1', email: 'user1@example.com' };
static readonly user2 = {id: 2, user_name: 'user2', email: 'user2@example.com', password: 'password' };
static readonly expected_user2 = {id: 2, user_name: 'user2', email: 'user2@example.com' };
static readonly allUsers = [
TestData.user1, TestData.user2
];
static readonly expected_allUsers = [
TestData.expected_user1, TestData.expected_user2
];
}

Then create DBSeedingService to set up the test data for UserController.

Press + to interact
// db-seeding.service.ts
@Injectable()
export class DBSeedingService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) {}
async seedUsers() {
await Promise.all(
TestData.allUsers.map((user) => this.userRepository.save(user)),
);
}
async cleanUsers() {
const existingUsers = await this.userRepository.find();
if (!existingUsers) {
return null;
}
return await this.userRepository.remove(existingUsers);
}
}

Here is the breakdown of the service:

  • Lines 4–7: These lines define the service’s constructor, which uses DI ...