22
Wed, May
2 New Articles

TechTip: Node.js Unit Testing

Scripting
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

 

You made a change. Did it break anything else? Not sure, unless you have automated testing.

Have you ever fixed one thing in your software only to find that you broke something else in the process? No? Me neither. So this article is for those "other people." OK, if I'm completely honest, I have bugs and I don't do a good job of automating my integration tests.

What are integration tests, how does one automate them, and how do they differ from “unit” tests? Good question. A unit test is a small bit of code that tests an API to make sure it functions as expected. An integration test focuses on a bigger-picture test and usually span across multiple API calls. This article will lean more toward integration testing.

If you haven't heard yet, IBM has open-sourced the Node.js iToolkit per this RFE (you need to register to access this site). This is an important step in the IBM i side of IBM embracing open source because it would be silly to pursue open source and then not allow community collaboration and contribution in order to follow in its footsteps of success. The source for the Node.js iToolkit can be found here. One of the first things I noticed about the project is it lacked any form of automating testing, so I logged an issue. The IBM Node.js team is quick to act, and they had some foundational integration tests in place in short order. Let's walk through the steps of obtaining the code, running the tests, and adding our own test.

I visited the Node.js iToolkit repo to obtain the below git clone command. Enter that command in a PASE shell and hit Enter.

% git clone This email address is being protected from spambots. You need JavaScript enabled to view it.:litmis/nodejs-itoolkit.git

Go into the newly created directory.

% cd nodejs-itoolkit

I am using the zsh shell, and it conveys my current directory as part of the prompt, as shown below. Use the ls command to learn the contents of the nodejs-itoolkit directory.

nodejs-itoolkit% ls -al

total 128

drwxr-sr-x    5 usr2l6ru 0              8192 Feb 28 16:35 .

drwxr-sr-x    9 usr2l6ru 0              8192 Feb 28 16:35 ..

drwxr-sr-x    8 usr2l6ru 0              8192 Feb 28 16:35 .git

-rw-r-----    1 usr2l6ru 0              1105 Feb 28 16:35 LICENSE

-rw-r-----    1 usr2l6ru 0               836 Feb 28 16:35 README.md

-rw-r-----    1 usr2l6ru 0                19 Feb 28 16:35 contributors.txt

drwxr-----    2 usr2l6ru 0              8192 Feb 28 16:35 lib

drwxr-----    2 usr2l6ru 0              8192 Feb 28 16:35 test

We can see that the test directory exists, so let's see what it contains via the ls command.

nodejs-itoolkit/test% ls -al

total 80

drwxr-sr-x    2 usr2l6ru 0              8192 Feb 28 16:35 .

drwxr-sr-x    5 usr2l6ru 0              8192 Feb 28 16:35 ..

-rw-r--r--    1 usr2l6ru 0               469 Feb 28 16:35 package.json

-rw-r--r--    1 usr2l6ru 0              4324 Feb 28 16:35 test.js

Whenever I see a package.json in a shell, I use the cat command to view it. The package.json file call tell you a lot about a Node.js application.

nodejs-itoolkit/test% cat package.json                  

{                                                                               

  "name": "nodejs-itoolkit-test",                                              

  "version": "1.0.0",                                                          

  "description": "",                                                            

  "main": "test.js",                                                           

  "scripts": {                                                                 

    "test": "mocha --no-exit test.js"                                           

  },                                                                           

  "repository": {                                                              

    "type": "git",                                                              

    "url": "git+https://bitbucket.org/litmis/nodejs-itoolkit.git"              

  },                                                                           

  "keywords": [                                                                 

    "nodejs-itoolkit"                                                          

  ],                                                                           

  "author": "Xu Meng",                                                         

  "license": "MIT",                                                            

  "homepage": "https://bitbucket.org/litmis/nodejs-itoolkit#readme",           

  "dependencies": {                                                            

    "mocha": "^3.2.0"                                                          

  }                                                                            

}

The two things to note are the scripts and dependencies sections. In dependencies, we see the mocha npm is being used, which is a Node.js testing framework. This lets us know we need to issue an npm install to obtain the necessary npms.

nodejs-itoolkit/test% npm install                       

npm WARN package.json nodejs-itoolkit-test@1.0.0 No description                

npm WARN package.json nodejs-itoolkit-test@1.0.0 No README data                

mocha@3.2.0 node_modules/mocha                                                 

??? diff@1.4.0                                                                  

??? browser-stdout@1.3.0                                                       

??? escape-string-regexp@1.0.5                                                 

??? growl@1.9.2                                                                

??? json3@3.3.2                                                                

??? commander@2.9.0 (graceful-readlink@1.0.1)                                  

??? supports-color@3.1.2 (has-flag@1.0.0)                                      

??? debug@2.2.0 (ms@0.7.1)                                                     

??? mkdirp@0.5.1 (minimist@0.0.8)                                              

??? lodash.create@3.1.1 (lodash._isiterateecall@3.0.9, lodash._basecreate@3.0.3,

 lodash._baseassign@3.2.0)                                                      

??? glob@7.0.5 (path-is-absolute@1.0.1, inherits@2.0.3, fs.realpath@1.0.0, once@

1.4.0, inflight@1.0.6, minimatch@3.0.3)

Now that we have mocha installed, we can attempt running the tests. Recall that there was an alias named "test" in the scripts section of packages.json. You can run those scripts by using the npm command and the script alias name.

nodejs-itoolkit/test% npm test

                                                                                

> nodejs-itoolkit-test@1.0.0 test  nodejs-itoolkit/test      

> mocha --no-exit test.js                                                      

  Basic Function Test

    Test iCmd()

      ? check the "success" property in return value (2884ms)

    Test iSh()

      ? check the "success" property in return value (3589ms)

    Test iPgm()

      ? check the "success" property in return value (723ms)

    Test iSql()

      ? check the "success" property in return value (3299ms)

  4 passing (12s)

All the tests passed! 

Next, let's take a look at the code in test.js. We know the tests are in test.js because of the package.json file.

var assert = require('assert');

var NodeVer = process.version.slice(1,2);

assert.notEqual(NodeVer, '0', 'Unsupported version of Node.js!');

var xt = require('/QOpenSys/QIBM/ProdData/OPS/Node'+NodeVer+'/os400/xstoolkit/lib/itoolkit');

var hint = 'check the "success" property in return value'

//Need change based on your server configurations

var opt = {

  db   : '*LOCAL',

  user : 'YOURNAME',

  pwd  : 'PASSWORD',

      host : '8.8.8.8',

      port : 8080,

      path : '/cgi-bin/xmlcgi.pgm'

};

describe('Basic Function Test', function() {

  this.timeout(5000)

  describe('Test iCmd()', function() {

    it(hint, function(done) {

      var conn = new xt.iConn(opt.db);

      conn.add(xt.iCmd('RTVJOBA USRLIBL(?) SYSLIBL(?)'));

      conn.run(function(str){

        var results = xt.xmlToJson(str);

        var success = true;

        results.every(function(result, i){

          if(result.hasOwnProperty('success'))

            success = result.success == true;

        });

        if(success) done();

        else done(new Error(JSON.stringify(results)));

      });

    });

  });

 

  describe('Test iSh()', function() {

    it(hint, function(done) {

      var conn = new xt.iConn(opt.db);

      conn.add(xt.iSh('system -i wrksyssts'));

      conn.run(function(str){

        var results = xt.xmlToJson(str);

        var success = true;

        results.every(function(result, i){

          if(result.hasOwnProperty('success'))

            success = result.success == true;

        });

        if(success) done();

        else done(new Error(JSON.stringify(results)));

      });

    });

  });

 

  describe('Test iPgm()', function() {

    it(hint, function(done) {

      var conn = new xt.iConn(opt.db);

      var pgm = new xt.iPgm('QWCRSVAL', {'lib':'QSYS'});

      var outBuf = [

          [0, '10i0'],

          [0, '10i0'],

          ['', '36h'],

          ['', '10A'],

          ['', '1A'],

          ['', '1A'],

          [0, '10i0'],

          [0, '10i0']

        ];

      pgm.addParam(outBuf, {'io':'out'});

      pgm.addParam(66, '10i0');

      pgm.addParam(1, '10i0');

      pgm.addParam('QCCSID', '10A');

      pgm.addParam(this.errno, {'io':'both', 'len' : 'rec2'});

      conn.add(pgm);

      conn.run(function(str){

        var results = xt.xmlToJson(str);

        var success = true;

        results.every(function(result, i){

          if(result.hasOwnProperty('success'))

            success = result.success == true;

        });

        if(success) done();

        else done(new Error(JSON.stringify(results)));

      });

    });

  });

 

  describe('Test iSql()', function() {

    it(hint, function(done) {

      var conn = new xt.iConn(opt.db);

      var sql = new xt.iSql();  /* Test iSql Class */

      sql.prepare('call qsys2.tcpip_info()');

      sql.execute();

      sql.fetch();

      sql.free();

      conn.add(sql);

      conn.run(function(str){

        var results = xt.xmlToJson(str);

        var success = true;

        results.every(function(result, i){

          if(result.hasOwnProperty('success'))

            success = result.success == true;

        });

        if(success) done();

        else done(new Error(JSON.stringify(results)));

      });

    });

  });

});

In reviewing the file, I noticed something that I believe needs fixing. Specifically, the test's success variable is defaulted to true, as shown below.

        var success = true;

I believe it would be best to default it to false and require the test to prove it was successful. That's a topic for another article.

One of the things I wanted to emphasize in this article is the ability for the community to add additional tests. In reviewing the existing tests, I noticed the sql.addQuery(…) didn't yet have a test, so I figured it would be good to create one.

To create a new test, I first copied an existing one and then started making changes. Below you can see my new integration test.

    it('should return SQL result set', function(done) {

      var conn = new xt.iConn(opt.db);

      var sql = new xt.iSql();

      sql.addQuery("SELECT LSTNAM, STATE FROM QIWS.QCUSTCDT");

      sql.fetch();

      sql.free();

      conn.add(sql);

      conn.run(function(str){

        var results = xt.xmlToJson(str);

        var success1 = false;

        var success2 = false;

        results.every(function(result, i){

          if(result.hasOwnProperty('success'))

            success1 = result.success == true;

          result.result.every(function(row, i){

            success2 = row[0].hasOwnProperty('desc');

          })

        });

        if(success1 && success2) done();

        else done(new Error(JSON.stringify(results)));

      });

    });

I added another level of testing in this one compared to the others. I am checking not only to see whether the XMLSERVICE result was a success, but also that the value returned from the SQL statement is what I'm expecting. BTW, the iToolkit is a wrapper over the RPG-based XMLSERVICE project in case you didn't know.

To run my test, along with the other tests, I go back to the below command.

nodejs-itoolkit/test% npm test                          

                                                                                

> nodejs-itoolkit-test@1.0.0 test /home/USR2L6RU/git/nodejs-itoolkit/test      

> mocha --no-exit test.js                                                      

                                                                                

  Basic Function Test                                                          

    Test iCmd()                                                                

      ? check the "success" property in return value (680ms)                    

    Test iSh()                                                                 

      ? check the "success" property in return value (2109ms)                  

    Test iPgm()                                                                 

      ? check the "success" property in return value (328ms)                   

    Test iSql()                                                                

      ? check the "success" property in return value (1921ms)                  

      ? should return SQL result set (500ms)                                   

                                                                               

  5 passing (7s)

The last test shown is the new test I created. It worked!

The next step is to commit these changes to the local git repo and then push them back to the nodejs-itoolkit Bitbucket repo. First, I run git status to see what changes have been made to this repo since the beginning of this article.

nodejs-itoolkit% git status                              

On branch master                                                               

Your branch is up-to-date with 'origin/master'.                               

Changes not staged for commit:                                                  

  (use "git add <file>..." to update what will be committed)                   

  (use "git checkout -- <file>..." to discard changes in working directory)    

                                                                               

        modified:   test/test.js                                               

                                                                               

Untracked files:                                                               

  (use "git add <file>..." to include in what will be committed)               

                                                                               

        test/node_modules/ 

In this case, I only want to commit test/test.js to the repo, so I will run the following two commands.

nodejs-itoolkit% git add test/test.js                   

nodejs-itoolkit% git commit -m 'Added new iSQL .addQuery(

) test'                                                                        

[master 037e123] Added new iSQL .addQuery() test                               

 1 file changed, 23 insertions(+)

And now it's time to push the changes to Bitbucket.

nodejs-itoolkit% git push origin master

Counting objects: 4, done.                                                    

Delta compression using up to 8 threads.                                      

Compressing objects: 100% (4/4), done.                                        

Writing objects: 100% (4/4), 613 bytes | 0 bytes/s, done.                     

Total 4 (delta 2), reused 0 (delta 0)                                          

To This email address is being protected from spambots. You need JavaScript enabled to view it.:litmis/nodejs-itoolkit.git                                

   ee59d1b..037e123  master -> master 

Now I can visit the commit history to see the changes, which are now shared with the world. Yee-haw!

You can contribute too. In a previous MCPressOnline article, I talked about how to do this using what are called "Pull Requests." Some tests that I know need to be added include the connection side of things. Also, the current tests test the "happy path," or they focus on things we expect to work. Well, what about things we expect to break? For example, how about a test that makes sure authentication with an invalid profile and password conveys the correct error?

If you have any questions or comments, then please comment below or email me at This email address is being protected from spambots. You need JavaScript enabled to view it..

Aaron Bartell

Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open-source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications andwww.litmis.comWith a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today's leading technologies, including Ruby on Rails, Node.js, Git for RPG source change management, and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today's modern application developers. Connect with Aaron via email atThis email address is being protected from spambots. You need JavaScript enabled to view it..

Aaron lives with his wife and five children in southern Minnesota. He enjoys the vast amounts of laughter that having a young family brings, along with camping and music. He believes there's no greater purpose than to give of our life and time to help others.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: