从窗口作用域函数调用的测试方法

Jasmine: testing method called from window scope function

本文关键字:测试方法 函数调用 作用域 窗口      更新时间:2023-09-26

我使用Jasmine来测试我的一些代码。它看起来有点像这样

# main logic
function Analytics() {
  this.construct = function() {
  }
  this.foo = function() {
  }
  this.bar = function() {
  }
}
# "main" routine, called by jQuery on ready, or direct by Jasmine
function analytics() {
  new Analytics().construct();
}
# calls main routine
$(document).ready(function () {
  analytics();
});

在浏览器中运行时,它工作得很好。然而,当我想用Jasmine测试我的代码时(测试在调用analytics()时是否调用了构造函数),它会失败。

Expected spy construct to have been called. (1)

说明如下:

it('should call the constructor when the document is ready', function({
    var _analytics = new Analytics();
    spyOn(_analytics, 'construct')
    analytics();  # note this is the "main" routine
    expect(_analytics.construct).toHaveBeenCalled();
})

我的测试用例似乎是不正确的,但我真的不知道如何。有人能解释一下这种行为吗?

正如我所看到的,从代码中"analytics"函数创建了analytics的新实例。

所以test可能是这样的:

it('should call the constructor when the document is ready', function({
    var _analytics = new Analytics(); // --> create new instance of Analytics
    spyOn(_analytics, 'construct') // --> spy on construct func
    analytics();  // --> This, creates new instance
    // of analytics which you don't spy on.
    expect(_analytics.construct).toHaveBeenCalled();
});

尝试通过prototype:

spyOn(Analytics.prototype, 'construct'); // will spy all instances.

和test将看起来像这样:

it('should call the constructor when the document is ready', function({
    spyOn(Analytics.prototype, 'construct');
    analytics();
    expect(Analytics.prototype.construct).toHaveBeenCalled();
});

注意你不能访问在分析函数中创建的实例。

创建后将无法使用。

我不知道任务的上下文。但也许你应该使用默认构造函数。

function Analytics(options) {
   // this is constructor
   this.prop1 = options.prop1;
   this.prop2 = options.prop2;
   this.foo = function() {
   }
   this.bar = function() {
   }
}
var analyticsModule = new Analytics(options);