E2E - Mocking MongoDB

This lesson is going to show you how to mock your data-source - MongoDB - for the E2E tests purpose. Thanks to using mongo-unit you will be able to perform actions that changes data in your DB, during E2E testing.

Mocking MongoDB#

E2E tests that you have written so far have one serious issue. They use the production database instance. That's a terrible design. Tests should never touch the production environment. Building the production version of the application for testing is good, but this application has a hardcoded database URL, which is bad. In this lesson, you will fix this issue. Apart from that, you will introduce a test that verifies if the user can add a product to the list of favorites.

Start by installing mongo-unit - a library that mocks MongoDB. Using a mock rather than a localhost MongoDB instance means you don't need to bother about database state - it's always the same. To install mongo-unit, type the following command in the terminal:

Now you need to prepare data that you want mongo-unit to return. Create a new file, e2e/testData.js, and add the following code:

Configuring Protractor#

The next step is to modify the Protractor configuration that is defined in e2e/protractor.conf.js. First of all, you need to introduce mongo-unit, child_process, and path:

You also need to set up a variable to hold a reference to the process that you are going to launch later:

And function, that you will use to delay the promise resolve:

Now modify the onPrepare() method to instantiate mongo-unit and launch a Node.js instance with the application that you're going to test. Add the following return statement to it:

The last step is to introduce the onComplete() method to shut down the Node.js instance that you've launched in onPrepare():

Your configuration file should now look like the following:

 

This page is a preview of The newline Guide to Angular Universal

Start a new discussion. All notification go to the author.