Setup test containers

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the Pain Free Mocking with Jest course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to Pain Free Mocking with Jest, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Pain Free Mocking with Jest
  • [00:00 - 00:05] To use test containers in our test, we first need to install it. So head over to the terminal and run this command.

    [00:06 - 01:40] Having installed the test container, I need to create a generic container and also get the connection string to our generic container. All will happen in the body of our describe block. And I also need to make a little trick to our app.js file and then lastly remove the MongoDB URI configuration value in our test.m. Okay, here I have test container setup for our test suite. And all we needed to do to create the test container was called generic container pass Mongo. We're basically saying create a MongoDB test container for us. And I used the with the exposed port to 7017. And we started our test container. Keep in mind that is an asynchronous operation. So we had to use our wait and we created the connection string to match MongoDB's connection string format using template strings. And also we updated the process.env and added MongoDB URI, which is our connection string based on the test container. After what we imported our server and our connection and safety in a global variable for our test suite. This is so that our after all hook will be able to close the connection and our server.

    [01:41 - 01:45] And finally, we also need to stop the container. Having done this, our head over to our app. js file.

    [01:46 - 02:10] And I will take out this line where we made our MongoDB URI unique using the just work ID. And lastly, I will take out our MongoDB URI from our test.env. So that's our application doesn't read it from here. Instead, it will get the MongoDB URI from the process.env.

    [02:11 - 02:32] I'll go ahead and run this test and all our tests should run without failing. So I envisaged that test containers will play a greater role in integration testing in the future.

    [02:33 - 02:43] So I'll advise that you get comfortable with test containers using them actually. It's quite easy and the benefits are in almost seeing in the next lesson.