Performing Unit Tests with Qunit

Objective

After completing this lesson, you will be able to run unit tests with Qunit

Unit Test with QUnit

Watch this short video to learn about unit testing.

The following figure provides an overview of QUnit.

Screen capture of the QUnit documentation website.

QUnit is a JavaScript unit and integration test framework. It is capable of testing any generic JavaScript code, the framework supports asynchronous tests out-of-the-box. It can be found at the following: http://api.qunitjs.com/

QUnit Test Example

QUnit uses a set of top-level functions to provide semantic meaning in unit tests.

Just like most of the unit test frameworks, it follows an arrange-act-assert pattern, a common test pattern employed during unit testing. Its purpose is to make a clear distinction between the set up for the test, the action that is to be tested, and the evaluation of the results.

Let's take a look at the important constructs.

Summary of Important Constructs

ConstructUsage
modulemodule(string) - defines a module.
testtest(string, function) - defines a test.
okok(boolean, string) - validates to true or false.
equalequal(value1, value2, message) - compares two values, using the double-equal comparator.
deepEqualdeepEqual(value1, value2, message) - compares two values based on their content, not just their identity.
strictEqualstrictEqual(value1, value2, message) - strictly compares two values, using the triple-equal comparator.
Sample QUnit code calling the module method then the test method.

Test Page

The following figure shows the code for an app that is about to be tested.

Sample code of a prettyDate function.

View the following video to learn about the test folder of an SAPUI5 project that is generated by SAP Business Application Studio, the details related to setting it up, and some examples.

Configuration of Unit Test Run

When you are using the SAPUI5 project template, which is provided by SAP Business Application Studio, all relevant aspects are generated to start the application under test mode using the unitTests.qunit.html file located in the unit-subfolder. To launch the application under the test start, Preview Application, from the menu in the project explorer of SAP Business Application Studio, or to open the file package.json located in the project, hover over the unit-tests-script and choose start script.

Screen capture of Business Application Studio. The Preview application has been called and the list displays different scripts to run. One of them is unit-tests fiori run.

Results of Unit Test Run

When the unit test is fully complete, a results screen is displayed. The following figure shows the results of the unit test run.

Screen capture of the results of a unit test showing errors.

Write Unit Tests

Business Example

In this exercise, you will write a unit test for a formatter.

Note

SAP Business Technology Platform and its tools are cloud services. Due to the nature of cloud software, step procedures and naming of fields and buttons may differ from the exercise solution.

Task 1: Create an SAP Fiori Freestyle Project

Steps

  1. Open your SAP Business Application Studio.

  2. Create a new SAP Fiori Freestyle project using the following information:

    SAP Fiori Freestyle Project Information

    FieldValue
    Template TypeSAP Fiori Generator
    TemplateBasic
    Data sourceNone
    View nameMain
    Module namequnit
    Application titleUnit Tests
    Application namespacestudent.com.sap.training.advancedsapui5
    DescriptionA Unit-test Application.
    Project folder path/home/user/projects

    Leave other fields and radio buttons on default value.

    1. Perform this step as shown in a previous exercise.

Task 2: Create the Function you will Test

You want to create a function to display dates in a pretty format.

Steps

  1. Add a file with the name Formatter.js into the webapp/model folder and implement the Formatter.js file, as shown in the following figure. Then save your work.

    Screenshot of the Formatter.js function code.

    Note

    if you prefer, you can upload the Formatter.js file located under Templates folder in the files you got from Github.
    1. Create or upload the Formatter.js file as shown in previous exercises.

    2. Write or Explore the code. You can use the following:

      Code Snippet
      1234567891011121314151617181920212223242526272829
      sap.ui.define([], function() { "use strict"; return { prettyDate : function (now, time) { var date = new Date(time || ""), diff = (((new Date(now)).getTime() - date.getTime()) / 1000), dayDiff = Math.floor(diff / 86400); if (isNaN(dayDiff) || dayDiff < 0 || dayDiff >= 3) { return; } var oResult = dayDiff === 0 && ( diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 600) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + "hours ago") || dayDiff === 1 && "Yesterday" || dayDiff < 7 && dayDiff + " days ago" || dayDiff < 31 && Math.ceil(dayDiff / 7) + "weeks ago"; return oResult; } } });

Task 3: Create the Unit Test

Steps

  1. Add a folder with the name model to the webapp/test/unit folder.

    1. Perform this step as shown in a previous exercise.

  2. Add a file with the name Formatter.js to the webapp/test/unit/model folder.

    1. Perform this step as shown in a previous exercise.

  3. Define a SAPUI5 module and add the dependency to the Formatter that you created in step 6.

    1. Add the following lines of code:

      Code Snippet
      123456
      sap.ui.define([ "student/com/sap/training/advancedsapui5/qunit/model/Formatter" ], function(Formatter) { "use strict"; });
  4. Add a QUnit module to the newly created SAPUI5 module. Use the QUnit.module function. As the module description, use Formatter and use the beforeEach hook to create a _formatter member variable with reference to the Formatter.

    1. Add the following lines of code after "use strict"; statement:

      Code Snippet
      123456
      QUnit.module("Formatter", { beforeEach: function () { this._formatter = Formatter; } });
  5. In the Formatter.js file, which is located in the webapp/test/unit/model folder, define a test case with the QUnit.test function. Use Test the pretty date implementation as the test case description. In the assigned function, create a variable with the name now. Assign the value 2008/01/28 22:25:00 to the now variable. Use the equal function of the assertion object to check if the date in the now variable is equal to the expected values in the following table. Print out the mentioned assertion messages.

    Hint

    You will use the prettyDate function of the Formatter as first argument of the equal function and the listed assertion messages as the second argument of the equal function.

    Expected Values and Corresponding Assertion Messages

    Expected ValueAssertion Message
    2008/01/28 22:25:00just now
    2008/01/28 22:24:001 minute ago
    2008/01/28 22:22:003 minute ago
    2008/01/28 21:25:001 hour ago
    2008/01/27 22:25:00Yesterday
    2008/01/26 22:25:002 days ago
    2007/01/26 22:25:00undefined
    1. Add the following lines of code after the QUnit.module function call:

      Code Snippet
      12345678910111213
      QUnit.test("Test the pretty date implementation", function(assert) { var now= "2008/01/28 22:25:00"; assert.equal(this._formatter.prettyDate(now,"2008/01/28 22:25:00" ), "just now"); assert.equal(this._formatter.prettyDate(now,"2008/01/28 22:24:00" ), "1 minute ago"); assert.equal(this._formatter.prettyDate(now,"2008/01/28 22:22:00" ), "3 minutes ago"); assert.equal(this._formatter.prettyDate(now,"2008/01/28 21:25:00" ), "1 hour ago"); assert.equal(this._formatter.prettyDate(now,"2008/01/27 22:25:00" ), "Yesterday"); assert.equal(this._formatter.prettyDate(now,"2008/01/26 22:25:00" ), "2 days ago"); assert.equal(this._formatter.prettyDate(now,"2007/01/26 22:25:00" ), undefined); });
    2. Save your work. Your Formatter.js file should now look like the following:

      Screenshot of the resulting code.

Task 4: Adjust namespaces

Steps

  1. Open the AllTests.js file and replace the given namespace with student/com/sap/training/advancedsapui5/qunit/test/unit/controller/Main.controller and student/com/sap/training/advancedsapui5/qunit/test/unit/model/Formatter.

    1. Open the AllTests.js file located in the unit folder of your project.

    2. Replace the given code with the following lines of code:

      Code Snippet
      12345678
      sap.ui.define([ "student/com/sap/training/advancedsapui5/qunit/test/unit/controller/Main.controller", "student/com/sap/training/advancedsapui5/qunit/test/unit/model/Formatter" ], function () { "use strict"; });
  2. Open the webapp/test/unit/controller/Main.controller.js file and adjust the namespaces. Replace the given namespace with student/com/sap/training/advancedsapui5/qunit/controller/Main.controller.

  3. Open the webapp/test/unit/unitTests.qunit.js file and adjust the actual namespace. Replace the given namespace with student/com/sap/training/advancedsapui5/qunit/test/unit/AllTests.

  4. Open the webapp/test/unit/unitTests.qunit.html file and adjust the resource roots configuration.

    1. Locate the data-sap-ui-resourceroots value allocation (probably at around line 9 – 15). Replace the value allocation with following:"student.com.sap.training.advancedsapui5/qunit": "../../"

Task 5: Run the Test

Steps

  1. Run your unit-tests and check the result.

    1. Open the context menu on your project folder qunit.

    2. Select Preview Application.

    3. Choose the option unit-tests fiori run –open text/unit/unitTests.qunit.html.

      Screenshot of the result of the QUnit test showing 1 failed test.

Log in to track your progress & complete quizzes