为什么Angular $ timeout会阻止端到端测试?

Jef*_*lle 7 timeout end-to-end angularjs

我做了一个指令,用于向用户显示通知消息.要显示我写的通知:

$scope.$watch($messaging.isUpdated, function() {
    $scope.messages = $messaging.getMessages();
    if ($scope.messages.length > 0) {
        $timeout(function() {
            for (var i = 0; i < $scope.messages.length; i++) {
                if (i + 1 < $scope.messages.length) {
                    $messaging.removeMessage($scope.messages[i]);
                } else {
                    $messaging.removeMessage($scope.messages[i]);
                }
            }
        }, 5000);
    }
});
Run Code Online (Sandbox Code Playgroud)

我正在使用$ timeout来确保消息在屏幕上停留5秒钟.

现在我想在其上编写End-To-End测试,以便我可以确定显示通知.问题是当显示通知时,End-To-End也与通知消息一样超时.这使得无法检查是否显示了正确的通知..

这是我的测试代码:

it('submit update Center', function() {
    input('center.Name').enter('New Name');
    input('center.Department').enter('New Department');
    input('center.Contact').enter('New contact');
    input('center.Street').enter('New street');
    input('center.City').enter('New city');
    input('center.Country').enter('New Country');
    element('button#center_button').click();

    expect(element('.feedback').count()).toBe(1);
    expect(element('.feedback:first').attr('class')).toMatch(/success/);

    expect(element('.error.tooltip').count()).toBe(0);
});
Run Code Online (Sandbox Code Playgroud)

我想避免使用javascript setTimeout()并希望有另一个(Angular)解决这个问题的方法.

Cai*_*nha 11

坏消息,朋友.这是AngularJs中的一个已知问题.这里有讨论,这里有一个"某种程度上相关"的问题.

幸运的是,您可以通过汇总自己的$timeout服务,手动呼叫setTimeout和呼叫来解决这个问题$apply(这是我所提到的讨论的建议).它真的很简单,虽然它真的很难看.一个简单的例子:

app.service('myTimeout', function($rootScope) {
  return function(fn, delay) {
    return setTimeout(function() {
      fn();
      $rootScope.$apply();
    }, delay);
  };
});
Run Code Online (Sandbox Code Playgroud)

请注意,这个与Angular不兼容$timeout,但如果需要,您可以扩展您的功能.