【问题标题】:Jasmine mocking a constructor within a functionJasmine 在函数中模拟构造函数
【发布时间】:2014-08-22 14:24:55
【问题描述】:

运行 Jasmine 测试时出现错误:'ReferenceError: JSZip is not defined'。这是我的控制器:

$scope.makeZip = function() {
    var zip = new JSZip();
    zip.file('myPhoto.txt', 'Hello World);
    return 'foo' + zip.generate();
};

并测试:

it('should make a zip with correct name', function() {
    var zipFileName = scope.makeZip();
    expect(zipFileName).toMatch('foo');
});

我的猜测是我需要以某种方式模拟 JSZip 构造函数:我尝试在测试开始时插入以下内容:

spyOn(window, 'JSZip').andReturn(null);

然后我得到“JSZip() 方法不存在”。 我认为这是与Jasmine - How to spy on a function call within a function? 类似的问题,但我找不到解决问题的正确方法。

有什么想法吗?感谢大家的帮助!

【问题讨论】:

  • 你能展示一下'makePhotos()'的函数吗?我只看到“makeZip”
  • 傻我,现在改名了
  • 哈哈,发生了。那么,一切都按预期工作了吗?
  • 不,不幸的是问题仍然存在......

标签: javascript angularjs unit-testing angularjs-scope jasmine


【解决方案1】:

JSZip 在窗口中定义。您不必将其传递给构造函数。在您的 jasmine 页面(存放规格的地方),reference jszip.js。如果你愿意,你可以创建一个服务..

你的角度模块.value("JSZip",JSZip);

然后将其传递给您的控制器。不过,这仅在您想模拟 JSZip 时才有用。

【讨论】:

    【解决方案2】:

    解决了!我实际上并不想测试 JSZip,只是为了检查函数 makeZip 是否被正确调用。

    it('should make a zip with correct name', function() {
        window.JSZip = function() {
                this.file = function() {};
                this.generate = function() {
                    return 'bar';
                };
            };
            var zipFileName = scope.makeZip();
            expect(zipFileName).toMatch('foo'); //makeZip should return string containing 'foo'
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-24
      • 2015-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2015-09-18
      • 2019-08-19
      相关资源
      最近更新 更多