Turn your manual testers into automation experts Request a DemoStart testRigor Free

Sails.js Testing

Sails.js Testing

Sails.js is a highly favored web application framework built on top of the Node.js runtime environment. Its popularity stems from its suitability for creating real-time features, making it an optimal choice for building customized enterprise applications with high data demands. Sails.js is built on Express.js, a high-performing backend web application platform capable of creating REST APIs. This relationship allows developers to swiftly create REST APIs using Sails.js.

The framework adheres to the model-view-controller (MVC) architectural pattern, providing a robust structure for web applications. Launched by Mike McNeil in 2012, Sails.js has been incorporated into over 10,000 websites globally. Its connectivity with Socket.io, a Javascript library for real-time and event-based system features, makes it even more powerful. This relationship enables developers to build real-time applications such as online chat platforms.

In addition, Sails.js integrates Waterline.js, an abstraction tool for database interaction. Waterline.js provides a uniform API irrespective of the database underlying the application. Sails.js has been adopted by major clients, including Amazon, Verizon, Postman, Microsoft, and Solarwinds, to name a few.

In this article, we'll delve into three testing strategies for Sails.js applications:

Unit Testing

Unit testing is the foundational step in the testing process, with the goal of identifying, isolating, and rectifying problematic code. When we perform unit testing, we scrutinize individual units of code. Mocha or Jest can facilitate unit testing for Sails.js applications.

Mocha

Mocha is a widely used JavaScript testing framework that simplifies the process of creating unit test scripts for Sails.js applications. All unit test scripts are stored in the /test directory. Before running the test cases, the Sails.js application must be started (a process known as "lifting" in Sails.js parlance), and it should be stopped or "lowered" once the testing is complete. This procedure can be handled by a lifecycle file, as shown below:
lifecycle.test.js
var sails = require('sails');
// Before running any tests...

before(function(done) {
  sails.lift({
    hooks: { grunt: false },
    log: { level: 'warn' },
  }, function(err) {
    return done();
  });
});
// After all tests have finished...
after(function(done) {
  sails.lower(done);
});
After creating the lifecycle file, let's consider a sample unit test code snippet:
describe('User (model)', function() {
  describe('#findBestStudents()', function() {
    it('should return 5 users', function (done) {
      User.findBestStudents()
        .then(function(bestStudents) {  
        if (bestStudents.length !== 5) {
          return done(new Error(
            'Should return exactly 5 students -- the students '+
            'from our test fixtures who are considered the "best".  '+
            'But instead, got: '+util.inspect(bestStudents, {depth:null})+''
          ));
        }
        return done();
      })
      .catch(done);
    });
  });
});

Jest

Jest is another popular open-source unit testing framework designed for JavaScript applications. However, integrating Jest with Sails.js can be complex and time-consuming. Therefore, for the purposes of this article, we will not delve into using Jest with Sails.js.

Integration Testing

Integration testing concentrates on assessing the interaction between different components, such as the model and view, the view and controller, or even the application's integration with external systems. For Sails.js applications, this type of testing can be carried out with a variety of tools, including Supertest or any browser testing tool. Integration testing checks the functionality of actions and controllers by sending HTTP requests and validating their responses. Additionally, this process can be performed using browser tests. For the purpose of this article, we will first discuss the usage of Supertest in Integration testing.

Supertest

Supertest is a modern nodejs library widely used for testing API's. It can be used as a standalone tool or integrated with other frameworks. For testing Sails.js, Supertest is used with the Mocha framework and Chai(another nodejs assertions library). Supertest is installed as a node package. Now let's see a sample integration test case written in Supertest.
var supertest = require('supertest');

describe('UserController.login', function() {
  describe('#login()', function() {
    it('should redirect to /my/page', function (done) {
      supertest(sails.hooks.HTTP.app)
      .post('/users/login')
      .send({ name: 'test', password: 'test' })
      .expect(302)
      .expect('location','/my/page', done);
    });
  });
});

To execute the test, you can use the Mocha command line. This will require passing arguments along with the 'mocha' command in the terminal. Alternatively, you can use the 'npm test' command, but this will require updating the script in the package.json file. In both cases, the lifecycle.test.js should be run first, as testing will be carried out in a local environment.

Browser testing tool

To test the integration between the View and Controller components, several tools can be used. Here are two examples:

  • Selenium-based tools - We won't delve into much detail here, as Selenium is a well-established tool with numerous online tutorials available.
  • testRigor - We will elaborate on the use of testRigor in the next section.

End-to-End Testing

End-to-End (E2E) testing is a comprehensive validation technique that assesses an application from start to finish, ensuring it fulfills user expectations. It confirms the proper functionality of all integrations with third-party applications and internal components. E2E testing primarily aims to simulate the end user's perspective. Test cases are framed as user flows, replicating and validating actual user scenarios for integration and data integrity at a high level. This form of testing often uncovers issues related to top-level components, request handling, and network configurations.

E2E testing for Sails.js applications can be conducted in several ways, with WebdriverIO and testRigor being among the most commonly used methods.

WebdriverIO

WebdriverIO is an open-source JavaScript testing framework that operates within a Node.js environment. This versatile automation tool is especially popular for Node.js applications. Supporting both JavaScript and TypeScript, WebdriverIO is rooted in the Behavior-Driven Development (BDD) approach. Moreover, it offers the flexibility to opt for the Cucumber, Jasmine, or Mocha testing frameworks.

Here's a basic example of a WebdriverIO script using Mocha:
import { browser, expect } from '@wdio/globals'

describe('Login Test is being started for user : ' + userName , function () {
  it('Should display the login page', async () => {
    await browser.url('https://samplesailssite.com')
  })
  
  it('Enter Email', async function () {
    await page.focus('#username_box')
    await page.keyboard.type(userName)
  });
  
  it('Enter Password', async function () {
    await page.focus('#password_box')
    await page.keyboard.type(userPass)
  });
  
  it('Click "Login in Here" button', async function () {
    await page.click('input[value="Log in Here"]'); // With type
    await page.waitForNavigation();    
  });
});

While WebdriverIO offers flexibility, it does require substantial infrastructure setup, making parallel execution complex when scaling across multiple devices. Testing mobile browsers necessitates reliance on the Appium framework. Additionally, WebdriverIO doesn't provide comprehensive built-in integration; each integration arrives as a node module package that needs to be installed separately. This can lead to conflicts during version updates, and establishing certain integrations can be challenging due to a lack of sufficient documentation. Building tests correctly is challenging, and maintaining these tests tends to be burdensome when using this tool.

testRigor

testRigor is a cloud-hosted no-code automation tool primarily designed for E2E testing. It supports a wide range of testing types, including web and mobile browser testing, mobile app testing, native desktop application testing, visual regression testing, API testing, load testing, and more.

One of the key strengths of AI-based testRigor is that it enables the creation of test scripts in plain English, which reduces dependency on programming language expertise. The tool can perform actions on elements just by identifying their name or position, such as select "MD" from dropdown, or click on image from stored value "Logo". This approach simplifies the scripting process, essentially allowing testers to transcribe manual test case steps.

testRigor also boasts other impressive features, including:

  1. Capability to create and execute test scripts on web and mobile browsers with minimal configuration changes.
  2. Test maintenance is virtually eliminated: AI engine helps make tests ultra-stable, and fixing tests that legitimately fail after code changes are extremely easy to debug and fix.
  3. Text validation on canvases and images using Optical Character Recognition (OCR).
  4. Verify 2-Factor Authentication (2FA) logins, including email, text message, and Google authenticator.

Moreover, testRigor supports numerous integrations, including CI platforms, infrastructure providers, test management and enterprise communication tools.

Here's an example of a simple test script:
login
click "Profile" to the left of "Users"
generate unique name, then enter into "First name" and save as "newName"
click "Update"
check that page contains stored value "newName"

Conclusion

Regardless of whether you are undertaking unit, integration, or end-to-end testing, it's critical to have a robust test plan and the right tools for each phase. We have explored various tools that can facilitate different stages of testing a Sails.js application. This guide should serve as a solid foundation as you embark on ensuring the reliability and robustness of your applications.