gpt4 book ai didi

javascript - Jasmine:从窗口范围函数调用的测试方法

转载 作者:行者123 更新时间:2023-11-28 20:54:12 25 4
gpt4 key购买 nike

我正在使用 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 实例。

所以可能测试是这样的:

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.

测试看起来像这样:

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);

关于javascript - Jasmine:从窗口范围函数调用的测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32312955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com