如何使用 Jasmine 测试匿名本地函数
How to test anonymous local functions with Jasmine
我的 Angular 代码中指令的 link 函数内部有以下构造(工具提示库可以在 http://iamceege.github.io/tooltipster/ 下找到):
scope.$on(MY_EVENTS.DATA_RETRIEVED, function(event) {
$timeout(function() {
var badge = element.find('.tooltip-hook');
badge.tooltipster({
content: $('Default tooltip'),
contentAsHtml: true,
theme: 'tooltipster-light',
functionBefore: function(origin, continueTooltipster) {
continueTooltipster();
origin.tooltipster('content', scope.getTooltip());
}
});
});
});
我遇到的问题是,当我用 Jasmine 测试这段代码时,报道记者抱怨说作为 functionBefore
传递的函数没有被我的测试覆盖。
我如何使用 Jasmine 对是否在显示工具提示之前调用此函数进行单元测试(从技术上讲,这不是测试我的代码而是测试工具提示代码)和(这是关于我的代码)还有里面的语句的功能被执行?要测试后者,我必须对已经匿名的本地函数的参数进行监视。
我知道我可以用 jasmine-jquery 插件模拟 mouseenter 事件,这应该会触发工具提示显示,但我如何用 Jasmine 单元测试覆盖 functionBefore
?
首先,测试tooltipster
是否调用该代码没有意义。正如您所说,测试框架是否正常工作没有意义。框架有(或应该有)自己的测试。
但是,您可以测试的是您传递给 tooltipster
的函数是否满足您的要求。
例如,您可以将 tooltipster
函数转换为 spy
:
var badge = ...
var passedObject;
//we are using a spy to get the object that is being passed to tooltipster
spyOn(badge, 'tooltipster').andCallFake(function (obj) {
passedObject = obj;
});
//TODO: wait for the $timeout function to be executed
var origin = jasmine.createSpyObj(...);
var continueTooltipster = jasmine.createSpy('continueTooltipster');
//now let's just test the function
passedObject.functionBefore(origin, continueTooltipster);
expect(continueTooltipster).toHaveBeenCalled();
这会起作用,但在这种情况下,我认为您不应该测试它。请注意,您应该测试有意义的东西,仅仅为了获得 100% 的覆盖率而测试所有东西是没有意义的。
我的 Angular 代码中指令的 link 函数内部有以下构造(工具提示库可以在 http://iamceege.github.io/tooltipster/ 下找到):
scope.$on(MY_EVENTS.DATA_RETRIEVED, function(event) {
$timeout(function() {
var badge = element.find('.tooltip-hook');
badge.tooltipster({
content: $('Default tooltip'),
contentAsHtml: true,
theme: 'tooltipster-light',
functionBefore: function(origin, continueTooltipster) {
continueTooltipster();
origin.tooltipster('content', scope.getTooltip());
}
});
});
});
我遇到的问题是,当我用 Jasmine 测试这段代码时,报道记者抱怨说作为 functionBefore
传递的函数没有被我的测试覆盖。
我如何使用 Jasmine 对是否在显示工具提示之前调用此函数进行单元测试(从技术上讲,这不是测试我的代码而是测试工具提示代码)和(这是关于我的代码)还有里面的语句的功能被执行?要测试后者,我必须对已经匿名的本地函数的参数进行监视。
我知道我可以用 jasmine-jquery 插件模拟 mouseenter 事件,这应该会触发工具提示显示,但我如何用 Jasmine 单元测试覆盖 functionBefore
?
首先,测试tooltipster
是否调用该代码没有意义。正如您所说,测试框架是否正常工作没有意义。框架有(或应该有)自己的测试。
但是,您可以测试的是您传递给 tooltipster
的函数是否满足您的要求。
例如,您可以将 tooltipster
函数转换为 spy
:
var badge = ...
var passedObject;
//we are using a spy to get the object that is being passed to tooltipster
spyOn(badge, 'tooltipster').andCallFake(function (obj) {
passedObject = obj;
});
//TODO: wait for the $timeout function to be executed
var origin = jasmine.createSpyObj(...);
var continueTooltipster = jasmine.createSpy('continueTooltipster');
//now let's just test the function
passedObject.functionBefore(origin, continueTooltipster);
expect(continueTooltipster).toHaveBeenCalled();
这会起作用,但在这种情况下,我认为您不应该测试它。请注意,您应该测试有意义的东西,仅仅为了获得 100% 的覆盖率而测试所有东西是没有意义的。