Oracle by Example brandingRun Unit Tests on a Node.js Microservice in Visual Builder Studio

section 0Before You Begin

This 10-minute tutorial shows you how to run unit tests on a Node.js microservice using Oracle Visual Builder Studio (VB Studio).

Background

Using the Node.js software libraries installed on the Build VM, VB Studio can run test scripts on Node.js applications.

In this tutorial, you'll complete these steps to run unit tests on the deployed Node.js microservice:

  • Create a Mocha test script file in the VB Studio Git repository. To know more about Mocha, see https://mochajs.org/.
  • Update the existing package.json file to include test dependencies
  • Configure a job in VB Studio to install the required Node.js software, accept the deployed microservice's URL as input at runtime, and then run the test script

What Do You Need?

  • A web browser
  • Your Oracle Cloud account credentials
  • The Docker, Node.js, and Kubernetes VM template configured in the previous deploy to OKE tutorial.
    Description of org_vmtemplate_software.png follows
    Description of the illustration org_vmtemplate_software.png
  • Node.js microservice's URL you deployed in the previous deploy to OKE tutorial. If you've deleted the deployed Kubernetes objects, run the deployment job again to deploy them and get the microservice's URL.

section 1Upload the Node.js Unit Test Script to the Git Repository

  1. Open the VB Studio project.
  2. In the left navigation menu, click Git.
  3. From the Repositories list, select my-nodejs-app.
  4. Click + File.
    Description of git_populated_repo.png follows
    Description of the illustration git_populated_repo.png
  5. In File Name, enter test.js.
  6. In the content area, copy and paste this script.
    Click Copy icon to copy the script.
    var rest_supertest = require("supertest");
    var should = require("should");
     
    // Enter your REST microservice app's URL here
    var rest_server = rest_supertest.agent(process.env.VAR_MICRO_URL);  //URL with build parameter input
     
    describe("Unit Tests for the REST Service",function(){
     
        // #1 Test if the REST URL is up
        it("should find the service to be running",function(done){
            rest_server
            .get("/")
            .expect("Content-type",/json/)
            .expect(200) // HTTP response
            .end(function(err,res){
                res.status.should.equal(200);
                res.body.error.should.equal(false);
                done();
            });
        });
     
        // #2 Test the main.js /add method
        it("should add two numbers",function(done){
            rest_server
            .post('/add')
            .send({num1 : 10, num2 : 20})
            .expect("Content-type",/json/)
            .expect(200)
            .end(function(err,res){
                res.status.should.equal(200);
                res.body.error.should.equal(false);
                res.body.data.should.equal(30);
                done();
            });
        });
     
        // #3 Test a non-existent method
        it("should return 404",function(done){
        rest_server
        .get("/subtract")
        .expect(404)
        .end(function(err,res){
            res.status.should.equal(404);
            done();
            });
        });
    });

    The above script performs these actions:

    • Defines variables for supertest and request
    • Using process.env.VAR_MICRO_URL, sets the input URL value. You'll define the VAR_MICRO_URL environment variable later when you configure the job.
    • Creates three tests:
      1. Checks whether the REST microservice is running
      2. Passes two numbers, 10 and 20, to the main.js file's /add method and verifies whether their sum equals 30
      3. Checks whether a non-existent /subtract method in main.js returns the 404 error code
  7. Click Commit.
  8. In the Commit Changes dialog box, click Commit.
  9. Next to Root Root of the repository, click / and select package.json.
    Description of git_open_file.png follows
    Description of the illustration git_open_file.png
  10. Click Edit Edit.
  11. In the content area, copy and paste this script.
    Click Copy icon to copy the script.
    {
      "name": "NodeJSMicro",
      "version": "0.0.1",
      "scripts": {
        "start": "node main.js",
        "test": "mocha test.js"
      },
      "dependencies": {
        "body-parser": "^1.19.0",
        "express": "^4.17.1"
      },
      "devDependencies": {
        "mocha": "^7.0.1",
        "should": "^13.2.3",
        "supertest": "^4.0.2"
      }
    }

    The above script updates the existing package.json to define the test script file and the command to run it. It also defines mocha, should, and supertest dependencies.

  12. Click Commit.
  13. In the Commit Changes dialog box, click Commit.

section 2Configure a Build Job

  1. In the left navigation menu, click Builds.
  2. In the Jobs tab, click + Create Job.
  3. In the New Job dialog box, enter these values and click Create.
    • Job Name: test-microservice
    • Description: Job to unit test the Node.js microservice using Mocha
    • Template: Node.js, Docker, and Kubernetes
    Description of new_job_dialog.png follows
    Description of the illustration new_job_dialog.png
  4. In the Configure Configure tab, click the Git tab.
  5. From Add Git, select Git.
  6. In Repository, select my-nodejs-app.git.
    Description of configure_job_sourcecontrol.png follows
    Description of the illustration configure_job_sourcecontrol.png
  7. In the Parameters tab, click Add Parameter and select String Parameter.
  8. In the parameter's fields, enter these values:
    • Name: VAR_MICRO_URL
    • Description: Enter the deployed microservice's URL in the http://<ip-address>:<port> format

    Here's an example:

    Description of configure_job_parameters.png follows
    Description of the illustration configure_job_parameters.png
  9. In the Steps tab, click Add Step, select Common Build Tools, and then select Unix Shell.
  10. Copy these commands and paste it in Script.
    npm install --save-dev mocha
    npm install --save-dev should
    npm install --save-dev supertest
    npm test
    When a build runs, the above commands install mocha, should, and supertest to the build's workspace and run the test.
  11. Scroll up and click Save.

section 3Run the Build Job

  1. On the test-microservice job's details page, click Build Now.
    Description of job_buildnow.png follows
    Description of the illustration job_buildnow.png
  2. In the Build Job dialog box, enter the deployed microservice's URL and click Build Now.

    Here's an example:

    Description of build_job_parameter.png follows
    Description of the illustration build_job_parameter.png
  3. Wait for the build to complete. If it's the VM's first build or the VM is in the Stopped state, the build will take some time.
  4. Click Build Log job_console_icon to see a similar build log and the unit test result.
    [2020-01-01 01:00:00] > mocha test.js
    [2020-01-01 01:00:00]   Unit Tests for the REST Service
    [2020-01-01 01:00:00]     ✓ should find the service to be running
    [2020-01-01 01:00:00]     ✓ should add two numbers
    [2020-01-01 01:00:00]     ✓ should return 404
    [2020-01-01 01:00:00]   3 passing (39ms)
    [2020-01-01 01:00:00] END shell script execution
  5. To fail a test, open the test.js file. In the left navigation menu, click Git, click test.js, and then click Edit Edit.
    Description of edit_file.png follows
    Description of the illustration edit_file.png
  6. In the script's /add method, change res.body.data.should.equal(30) to res.body.data.should.equal(40).
    // #2 Test the main.js /add method
    it("should add two numbers",function(done){
    	rest_server
    	.post('/add')
    	.send({num1 : 10, num2 : 20}) // input numbers
    	.expect("Content-type",/json/)
    	.expect(200)
    	.end(function(err,res){
    		res.status.should.equal(200);
    		res.body.error.should.equal(false);
    		res.body.data.should.equal(40); // expected sum
    		done();
    	});
    });
  7. Click Commit.
  8. In the Commit Changes dialog box, click Commit.
  9. In the left navigation menu, click Build.
  10. In the Jobs tab, click test-microservice.
  11. Click Build Now.
    Description of job_buildnow.png follows
    Description of the illustration job_buildnow.png
  12. In the Build Job dialog box, enter the deployed microservice's URL and click Build Now.
  13. Wait for the build to complete. The build fails because a test failed.
  14. Click Build Log job_console_icon to see a similar build log and the failed unit test result.
    [2020-01-01 01:00:00] > mocha test.js
    [2020-01-01 01:00:00]   Unit Tests for the REST Service
    [2020-01-01 01:00:00]     ✓ should find the service to be running
    [2020-01-01 01:00:00]     1) should add two numbers
    [2020-01-01 01:00:00]     ✓ should return 404
    [2020-01-01 01:00:00]   2 passing (41ms)
    [2020-01-01 01:00:00]   1 failing
    [2020-01-01 01:00:00]   1) Unit Tests for the REST Service
    [2020-01-01 01:00:00]        should add two numbers:
    [2020-01-01 01:00:00]       Uncaught AssertionError: expected 30 to be 40
    [2020-01-01 01:00:00]       + expected - actual
    [2020-01-01 01:00:00]       -30
    [2020-01-01 01:00:00]       +40
    [2020-01-01 01:00:00]       
    .
    .
    .
    [2020-01-01 01:00:00] npm ERR! Test failed.  See above for more details.
    [2020-01-01 01:00:00] Error: Command exited with status 1
    [2020-01-01 01:00:00] END shell script execution