【发布时间】:2016-09-28 06:41:47
【问题描述】:
我有一个指令,它的行为应该有所不同,具体取决于自初始化以来经过的时间:
am.directive('showText', () => ({
restrict: 'E',
replace: true,
scope: {
value: '@'
},
controller: ($scope, $timeout) => {
console.log('timeout triggered');
$scope.textVisible = false;
let visibilityCheckTimeout = $timeout(() => {
if (parseInt($scope.value, 10) < 100) {
$scope.textVisible = true;
}
}, 330);
// Clear timeout upon directive destruction
$scope.$on('$destroy', $timeout.cancel(visibilityCheckTimeout));
},
}));
问题是,当我尝试使用 Jasmine 对其进行测试时,我似乎无法找到以任何方式触发此超时的方法。已经尝试过$timeout.flush() 和$timeout.verifyNoPendingTasks()(如果我要评论flush 调用,实际上会引发错误)。但它仍然没有触发超时的回调执行
describe('showText.', () => {
let $compile;
let $rootScope;
let $scope;
let $timeout;
const compileElement = (rootScope, value = 0) => {
$scope = rootScope.$new();
$scope.value = value;
const element = $compile(`
<show-text
value="value"
></show-text>
`)($scope);
$scope.$digest();
return element;
};
beforeEach(() => {
module('app.directives.showText');
inject((_$compile_, _$rootScope_, _$timeout_) => {
$compile = _$compile_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
});
});
it(`Process lasts > 0.33s. Should show text.`, () => {
const VALUE = 30;
const element = compileElement($rootScope, VALUE);
const elementContent = element.find('.show-text__content');
$timeout.flush(1000);
$timeout.verifyNoPendingTasks();
$rootScope.$digest();
expect(element.isolateScope().textVisible).toBeTruthy();
expect(elementContent.length).toEqual(1);
expect(elementContent.text().trim()).toBe('Example text');
});
});
测试失败。
找不到我做错了什么。有关如何正确测试这种情况的任何提示?
谢谢。
UPD
经过一番调查,我发现在这个特定的测试用例中,compileElement 函数中,value 属性没有被$compile 服务评估。等于"value"。我已经使用了 10 次相同的函数,但无法理解为什么它不像以前那样使用 $scope.value 的属性。
【问题讨论】:
-
你怎么知道没有运行超时,你用断点检查了吗?
-
@estus 带有断点,以及在其中放置控制台日志。还删除了这个“if”语句并检查属性
textVisible是否更改。通常在将console.logs 放入其中时,它们会在终端的测试用例之间给出输出。目前正在尝试使用 $scope 公开超时的回调,并对其进行监视。 -
@estus 向问题添加了“更新”。似乎由于某种原因,
$compile服务未评估传递的值。