gpt4 book ai didi

angularjs - 如何使用 Jasmine 的 debounce 功能测试 AngularJS watch

转载 作者:行者123 更新时间:2023-12-04 15:22:30 26 4
gpt4 key购买 nike

我有一个带 watch 的 Controller ,它使用 lodash 的去抖动将列表过滤延迟 500 毫秒。

$scope.$watch('filter.keywords', _.debounce(function () {
$scope.$apply(function () {
$scope.filtered = _.where(list, filter);
});
}, 500));

我正在尝试编写一个 Jasmine 测试,该测试模拟输入未找到的过滤器关键字,然后是找到的关键字。

我最初的尝试是在为关键字分配新值后使用 $digest ,我认为由于去抖动而不起作用。
it('should filter list by reference', function () {
expect(scope.filtered).toContain(item);
scope.filter.keywords = 'rubbish';
scope.$digest();
expect(scope.filtered).not.toContain(item);
scope.filter.keywords = 'test';
scope.$digest();
expect(scope.filtered).toContain(item);
});

所以我尝试使用 $timeout,但这也不起作用。
it('should filter list by reference', function () {
expect(scope.filtered).toContain(item);
$timeout(function() {
scope.filter.keywords = 'rubbish';
});
$timeout.flush();
expect(scope.filtered).not.toContain(item);
$timeout(function() {
scope.filter.keywords = 'test';
});
$timeout.flush();
expect(scope.filtered).toContain(item);
});

我也试过给 $timeout 一个大于去抖动设置的 500ms 的值。

其他人是如何解决这个问题的?

编辑:我找到了一个解决方案,它将期望包装在 $timeout 函数中,然后在作用域上调用 $apply。
it('should filter list by reference', function () {
expect(scope.filtered).toContain(item);
scope.filter.keywords = 'rubbish';
$timeout(function() {
expect(scope.filtered).not.toContain(item);
});
scope.$apply();
scope.filter.keywords = 'test';
$timeout(function() {
expect(scope.filtered).toContain(item);
});
scope.$apply();
});

我仍然有兴趣知道这种方法是否最好。

最佳答案

这是一个糟糕的方法。您应该使用特定于 Angular 的去抖动,例如 this使用 $timeout 而不是 setTimeout。这样,你可以做

  $timeout.flush();
expect(scope.filtered).toContain(item);

并且规范将按预期通过。

关于angularjs - 如何使用 Jasmine 的 debounce 功能测试 AngularJS watch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24167644/

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