在单元测试中调用外部函数

Call external function in unit test

本文关键字:外部 函数 调用 单元测试      更新时间:2023-09-26

我正在学习单元测试;我是一个OpenUi5开发者,我每天都使用Webstorm IDE。Webstorm允许我配置Karma运行配置。我已经创建了一个简单的karma配置文件,并编写了一个测试文件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;
};

好!Sum函数在同一个文件中。但现在我想开始测试功能在我的js文件夹的项目(单元测试在test-resources文件夹);例如,在js/util.js我有getShortIdGrid功能:

//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'" );
    });

如何在测试中调用ui5bp.controlgetShortIdGrid ?

Karma console show me ReferenceError: ui5bp is not defined.

正确加载util.js文件后,我如何管理顶部的声明jQuery.sap.declare("ui5bp.control"); ?我想测试我的简单函数,而不涉及完整的库!

您需要确保unit.js包含在karma配置文件files属性中,以使其可用于karma。例如,如果你的unit.js位于/src文件夹中,而你的specs位于/tests文件夹中,那么它看起来如下:

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: [],
...

这足以让ui5bp解析