【问题标题】:Call external function in unit test在单元测试中调用外部函数
【发布时间】:2015-08-28 10:13:26
【问题描述】:

我正在尝试学习 qunit 测试;我是一名 OpenUi5 开发人员,我每天都使用 Webstorm IDE。 Webstorm 允许我配置 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 is not defined

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

【问题讨论】:

  • 你是如何在测试中包含 util.js 文件的?它会导出ui5bp 对象吗?
  • 这正是问题所在:我不知道如何包含unit.js 。使用 Openui5 框架,要使用 controlgetShortIdGrid 函数,我通常根据需要定义 `jQuery.sap.require("js.util");` 在我的 Component 文件和 util.js 文件顶部的文件我写 jQuery.sap.declare("ui5bp.control"); 然后我可以通过ui5bp.control.getShortIdGrid调用函数

标签: javascript unit-testing karma-runner webstorm sapui5


【解决方案1】:

您需要确保 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

【讨论】:

  • 谢谢莉娜,现在业力见 util.js 文件!但是我现在有一个问题:在 util.js 文件的顶部我有jQuery.sap.declare("ui5bp.control");,需要由 openui5 框架显示该文件,控制台显示此错误:Uncaught TypeError: Cannot read property 'declare' of undefined at http://localhost:9876/base/WebContent/js/util.js?b78f8003cbcefeb1a02ed1e325797c167e83bf9d:1
  • 答案还是一样 - 要让 karma 解析您使用的所有类型,您需要确保在其配置文件中包含相应的文件
猜你喜欢
  • 2015-11-13
  • 2022-01-01
  • 2015-07-09
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 2021-07-20
相关资源
最近更新 更多