Search code examples
javascriptunit-testingkarma-runnerwebstormsapui5

Call external function in unit test


I'm trying to learn qunit test; I'm an OpenUi5 developer and I use Webstorm IDE every day. Webstorm allows me to config a Karma run configuration. I have created a simple karma configuration file and I have wrotten a test file test1.js:

test("Test function sum()",
  function() {
    ok(sum(0, 0) == 0, "the sum of 0 with 0 is 0");
    ok(sum(2, 0) == 2, "the sum of 2 with 0 is 2");
    ok(sum(2, 1) == 3, "the sum of 2 with 1 is 3");
    ok(sum(2, -1) == 1, "the sum of 2 with -1 is 1");
    ok(sum(-2, 1) == -1, "the sum of -2 with 1 is -1");
  });


function sum(a, b) {
  return a + b;
};

Good! sum function is inside the same file. But now I want start to test functions in my js folder of the project (the unit test are in test-resources folder); for example in js/util.js I have getShortIdGrid function:

//util.js file
jQuery.sap.declare("ui5bp.control");

ui5bp.control = {
  ...
  getShortIdGrid: function(sFromId) {
      if (sFromId.lastIndexOf("_") < 0)
        return sFromId;
      else
        return sFromId.substring(0, sFromId.lastIndexOf("_"));
  },
  ...
}

and this is my the my test:

test("test getShortIdGrid",
    function () {
        equal( ui5bp.control.getShortIdGrid("shortId_123"), "shortId" ,"ShortIdGrid of 'shortId_123' is 'shortId'" );
    });

How can I call ui5bp.controlgetShortIdGrid in my test?

Karma console show me ReferenceError: ui5bp is not defined.

After loading properly the util.js file, how can I mange the declaration jQuery.sap.declare("ui5bp.control"); on the top? I would like test my simple function without reloat the full library!


Solution

  • You need to make sure that unit.js is included in karma configuration file, files property, to make it available to karma. For example, if you have your unit.js located in /src folder, whereas your specs are in /tests, it would look as follows:

    module.exports = function (config) {
        config.set({
    
            // base path, that will be used to resolve files and exclude
            basePath: '',
            frameworks: ['qunit'],
            files: [
                'tests/**/*.js',
                'src/*.js'
            ],
            exclude: [],
    ...
    

    That's enough to get ui5bp resolved