如何在jasmine测试用例中模拟$(element).show和ko.mapping.fromJS

How to mock $(element).show and ko.mapping.fromJS in jasmine test case?

本文关键字:show element ko fromJS mapping jasmine 测试用例 模拟      更新时间:2023-09-26

这是我的代码:

TestViewModel.prototype.edit = function(pId, pData) {
    self.modalId = '#header';
    $(self.modalId).modal('show'); //error
    self.id(ko.mapping.fromJS(pData).id()); //how to mock this ?
}        

这是Jasmine测试用例:

  it("calling edit method", function() {
        var modalId = $("#cc-accessControlUserModal");
        var EditData = {id:"i10060"};
        spyOn($.fn, 'modal');
        self.TestViewModel.edit("i10060",EditData);
  });

然而,这将给我:

错误:modal()方法不存在

所以,问题是:如何在Jasmine测试用例中模拟$(element).showko.mapping.fromJS

这是一个老问题,但我最近遇到了同样的问题。如果您正在使用karma运行jasmine脚本,请将引导程序库添加到文件下的karma.config文件中。

files: [
      'node_modules/es6-shim/es6-shim.js',
      'node_modules/reflect-metadata/Reflect.js',
       ...
      'node_modules/jquery/dist/jquery.min.js',
      'node_modules/jquery-mask-plugin/dist/jquery.mask.js',
      'node_modules/jquery-ui/ui/core.js',
      'node_modules/jquery-ui/ui/datepicker.js',
      //Append dependencies to this list
      'node_modules/bootstrap/js/modal.js',
...
]

在我的例子中,由于我不需要整个引导程序库,所以我只包含了模式文件。

这是karma配置文档:karma doc