javascript - 如何测试模型中依赖于 Controller 的函数

标签 javascript sapui5 sinon qunit

我有一个像这样的格式化程序文件

sap.ui.define([], function() {
  "use strict";    
  return {       
    someFunction: function(sKey) {
      var sResult = "";
      var model = this.getModel("somekey");
      if (model) {
        var oItem = model.getProperty("/yesno")[parseInt(sKey) - 1];
        if (oItem) {
          sResult = oItem.Name;
        }
      }
      return sResult;
    }
  };
});

模型是在 Controller onInit 函数中定义的,如下所示

this.setModel(new sap.ui.model.json.JSONModel(this._somekey), "somekey"); 

onInit: function() {
    // object containing the model data for header dropdowns
    this._somekey = {
      //uses ResourceBundle here
      ............
      ...........
    }
}

现在我想在格式化程序中测试 someFunction。我不知道我该怎么做?

我尝试过这样

var oModel = this.stub();
oModel.withArgs("headerDropdowns").returns(/* donno what to return here */);
    var oControllerStub = {
        getModel:  oModel
    };

var fnIsolatedFormatter = formatter.someFunction.bind(oControllerStub);
assert.strictEqual(fnIsolatedFormatter.someFunction("1"), "dropdown string do not match");                  
});

最佳答案

sap.ui.define([
  ".../formatter",
  "sap/ui/model/json/JSONModel"
], function(formatter) {
  "use strict";

  QUnit.module("someFunction");

  QUnit.test("Should do this and that", function(assert) {
    formatter.getModel = function() {
      return new JSONModel({ "yesno": "<whatever>" });
    };

    var sResult = formatter.someFunction("abc");

    assert.equal(sResult, "xyz");
  }
});

关于javascript - 如何测试模型中依赖于 Controller 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51518606/

相关文章:

c# - ASP.Net WebAPI Post 方法显示空值

javascript - UI5 TreeTable 滚动到以编程方式绑定(bind)到表的模型中的指定项目

sapui5 - sap.ui.table.Table 如何优化列宽

node.js - 链中的 stub Nodejs Promise 返回错误

Node.js - 单元测试中间件

javascript - Phonegap + JQuery 无法连接到互联网

javascript - 如何显示/隐藏多个 div

javascript - 扩展 sap.m.Table 中的事件未触发

javascript - 使用 SinonJS stub (带重新布线)

javascript - Angularjs 路由不适用于基本 href