Visual Builder makes it very easy to adopt test driven development with declarative test creation for action chains.  You can find lots of information on testing action chains in the docs.

In this blog we'll show you how to create tests and how to mock REST calls as part of these tests.

What is Unit Testing?

A Unit Test tests a small isolated section, or "Unit", of code.  A unit of code should be a small section of code that can be isolated and tested without external dependencies, but large enough to make sense when you ask "what does this unit do?".  When you have small isolated tests, they will run fast and fail fast.  These tests can be automated to constantly run while you are developing.  This gives you an immediate notification if a new bug is introduced while you're modifying the code.

What is a Mock?

Sometimes the unit of code you want to test will include calls to external functionality.  This could be a database query, another function, or a REST API.

Your unit will behave differently based on the results of these calls, but a "Unit Test" should not depend on the external code functioning properly.  Your unit test should only consider specific expected behavior from dependencies.  For example, "I send X to the service and it will return Y".  If the dependency is broken, your unit tests should still be able to run. Making sure all parts of the process work together is a different kind of test.

In order to make this work, you will fake or "mock" these external dependencies.  You choose a scenario for the external call and create a mock that "pretends" to make the call and return the expected results.  This way you are only testing the specific defined "Unit" of code.

There are lots of testing frameworks available for all kinds of software development.

In this guide we will learn how to mock a REST call in a Visual Builder unit test.

Pre-Setup

For the examples I've created the following:

  • A Service Connection for the "GET ONE" REST service "https://restcountries.com/v2/alpha/{country}".
  • A Web App with a single button.  When pressed it will execute an action chain passing "US"  into the action chain's countryCode Input Parameter to be used in the above REST call.

The Action Chain does the following:

  • Makes a call to the above REST service passing the countryCode input parameter into the Service Connection Path Parameter
  • If the Response is not OK, it fires a notification of "Error" for Errors
  • If the Response is OK, it fires a notification showing the country capital from the Response Body.
  • At the end it Returns the Status Code from the Response.

Action Chain

define([
  'vb/action/actionChain',
  'vb/action/actions',
  'vb/action/actionUtils',
], (
  ActionChain,
  Actions,
  ActionUtils
) => {
  'use strict';

  class ButtonActionChain extends ActionChain {

    /**
     * @param {Object} context
     * @param {Object} params
     * @param {string} params.countryCode 
     * @return {number} 
     */
    async run(context, { countryCode }) {
      const { $page, $flow, $application, $constants, $variables } = context;

      const response = await Actions.callRest(context, {
        endpoint: 'country/getAlphaCountry',
        uriParams: {
          country: countryCode,
        },
      });

      if (!response.ok) {
        await Actions.fireNotificationEvent(context, {
          summary: 'Error',
        });
      } else {
        await Actions.fireNotificationEvent(context, {
          summary: response.body.capital,
        });
      }

      return response.status;
    }
  }

  return ButtonActionChain;
});

Create a Unit Test

In the action chain click "Tests" at the top of the screen.

Tests Button

 Click "+ Test"

Add Test

Set the test name to "Returns Error".

Returns Error

Enter a value in the countryCode "Parameters" box and click "Save".  Remember, we're mocking the call so the actual value doesn't matter.

Country Code

An empty Mock has been stubbed in automatically.  Click the Mock.

Click The Mock

The external REST API will not be called.  Instead, we'll define the values that would be expected if the API was not found.

Set the following values:

  • Status: 404
  • Status Text: Not Found
  • OK: false

Click Save.

Error Mock Properties

We expect two things to happen at this point.

  1. A notification will fire with a summary of "Error"
  2. The Action Chain will return the status "404" from the mock

Click the "Get Suggestions" button below Expectations.

Error Get Expectations

Both of the above expectations are suggested by Visual Builder.

Click "Add All".

Error Add All Expectations

The first Unit Test is defined.

Run the Test

Error Run Test

The test should pass.

Error Test Pass

Test for Success

Now let's test the "Success" condition.

To save a little bit of work, right click on the "Returns Error" test and select "Duplicate".

Duplicate Test

Change the test name to "Returns Country Object".

Success Name Test

You can leave the countryCode parameter value.  It still doesn't matter.

Click on the mock.

Success Click The Mock

This time we're using a value from the Response body in the notification, so we'll need to mock the body.  You could just define you're own JSON object and test for that, but sometimes the object may be a little more complex and you might want use an object that matches the real call.

Click on "Make a REST request to get result data for this mock".  This will take you to the "Test" tab of your service definition.

Success Mock Properties

Enter a valid value for any parameters used in your test.  In this case it's the country code.

Click "Send Request".

Send Request

Copy the body of the Response.

CopyBody

Switch back to your Action Chain Test and paste the body into the Mock Body field.

Set the following values:

  • Status: 200
  • Status Text: OK
  • OK: true

Click Save.

Success Paste Body

Run the Test

When you run this test, it fails.

We still have the expectations from the duplicated Error Test, but we have the Mocked values for a Success response so the test fails.

You can see in the failed test that it expected summary to equal "Error" but in this case it was "Washington, D.C.".

Failed Test

Use the trash can icon to delete both expectations from the test.

Delete Expectations

When the REST call succeeds, we expect two things to happen.

  1. A notification will fire with a summary of "Washington, D.C."
  2. The Action Chain will return the status "200" from the mock

Click on "Get Suggestions".

Success Get Suggestions

These are both suggested by Visual Builder.

Click "Add All".

Success Add All

This time we'll run the tests from the bottom "Tests" area.

At the bottom of the screen, click "Tests", then click the "Run All" button.

You will see that both of your tests run and the both pass.

Success Run All

Visual Builder has built in Unit Test automation.  After you add Unit Tests, keep an eye on this tab while you work on your application.  The tests will auto run periodically, and if you make a change that causes a test to fail, you will be notified on this tab.

Success Auto Run Failed

Visual Builder has a robust Unit Testing tool.  Hopefully, once you see how easy it is to write unit tests you'll write more.

Remember, the better your testing is, the better your application will be.