efw*_*mes 7 javascript unit-testing angularjs
我有一个Angular指令"clock",我正在尝试编写一个单元测试来查看时钟实际$ interval是否会提前到未来时间(即:通过查看2分钟element.text()).我对当前时间进行了测试,现在我想测试它是否会显示未来的时间$interval.flush.在我看来,它$interval.flush并没有真正推进时钟.
我可以要求两个答案:
$interval发生火灾,我该如何进行单元测试?$interval.flush似乎没有推进Date()?我正在遵循这些帖子的指导原则:
一篇相关文章建议使用Jasmine模拟,我认为这是不再需要的.
一个类似的问题:
<mydatething format="EEEE, MMMM d" interval="1000" timezone="notused"></mydatething>
Run Code Online (Sandbox Code Playgroud)
myApp.directive('mydatething', ['$interval', 'dateFilter', function ($interval, dateFilter) {
return {
restrict: "AE",
scope: {
format: '@',
interval: '@'
},
template: '', // the template is the Date() output
link: function (scope, element, attrs) {
// scope expects format, interval and timezone
var clockid;
var clockinterval = scope.interval;
var dateformat = scope.format;
var clocktimezone = scope.timezone;
// DOM update function
function updateClock() {
element.text(dateFilter(new Date(), dateformat));
}
// Instantiate clock
updateClock();
clockid = $interval(updateClock, clockinterval); // fixed
// For cancelling
scope.$on('$destroy', function () {
$interval.cancel(clockid);
});
// Separate listener for locale change, manually refresh clock format
scope.$on('$localeChangeSuccess', function () {
updateClock();
})
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
describe("tsdate directive", function(){
var elem, scope, $interval, dateFilter;
beforeEach(module('tsApp'));
beforeEach(inject(function(_$rootScope_, _$interval_, _$compile_, _dateFilter_){
$compile = _$compile_;
dateFilter = _dateFilter_;
$interval = _$interval_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
elem = angular.element('<mydatething format="h:mm a" interval="15000"></mydatething>');
elem = $compile(elem)(scope);
scope.$digest();
}));
describe('on clock start', function() {
it('to show the current date', function() {
var currentdate = dateFilter(new Date(), elem.isolateScope().format);
expect(elem.text()).toBe(currentdate);
// this passes
});
it('that it updates the clock', function() {
var futurems = 120000; // 2 minutes
var futuredate = dateFilter(new Date().getTime() + futurems, elem.isolateScope().format)
$interval.flush(futurems);
expect(elem.text()).toBe(futuredate);
// this fails
});
});
});
Run Code Online (Sandbox Code Playgroud)
PhantomJS 1.9.8 (Mac OS X) mydatething directive on clock start that it updates the clock FAILED
Expected '3:55' to be '3:57'.
Run Code Online (Sandbox Code Playgroud)
Console.log显示,futuredatevar增加2分钟,但elem.text()仍然是当前时间.
开始之前请注意:
您的指令代码有错误。调用 $interval 时,将函数对象作为第一个参数传递。没有括号。
// Do this
clockid = $interval(updateClock, clockinterval);
// Not this
clockid = $interval(updateClock(), clockinterval);
Run Code Online (Sandbox Code Playgroud)
看看plunker上的区别
其次,调用 $interval.flush 会导致间隔向前移动毫秒数,但不会影响内部 Javascript 时钟。由于您使用 Date 来更新时钟上的时间,因此您始终会获得当前时间。调用 $interval.flush 可能会导致interval多次更新时钟,但它总是将其设置为当前时间。
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |