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

Call external function in unit test

我正在努力学习 qunit 测试;我是一名 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("_"));
  },
  ...
}

这是我的测试:

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

如何在测试中调用 ui5bp.controlgetShortIdGrid

Karma 控制台显示 ReferenceError: ui5bp 未定义.

正确加载 util.js 文件后,如何管理顶部的声明 jQuery.sap.declare("ui5bp.control");?我想在不重新加载整个库的情况下测试我的简单函数!

您需要确保 unit.js 包含在 karma 配置文件中,files 属性,以便 karma 可以使用它.例如,如果您的 unit.js 位于 /src 文件夹中,而您的规范位于 /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