Подтвердить что ты не робот

Javascript.confirm() и Angularjs Karma e2e test

У меня есть приложение Angularjs, которое использует простой javascript-подтверждение перед выполнением некоторых действий.

Контроллер:

function TokenController($scope) {
  $scope.token = 'sampleToken';

  $scope.newToken = function() {
    if (confirm("Are you sure you want to change the token?") == true) {
      $scope.token = 'modifiedToken';
    }
  };
}

Вид:

<div id="tokenDiv">
  Token:{{token}} <button ng-click="newToken()">New Token</button>
</div>

Теперь я хочу пройти тест конца, чтобы проверить, что токен правильно заменяется в представлении. Как перехватить вызов javascript.confirm(), чтобы он не остановил выполнение теста?

Тест:

it('should be able to generate new token', function () {
   var oldValues = element('#tokenDiv').text();
   element('button[ng-click="newToken()"]').click(); // Here the javascript confirm box pops up.
   expect(element('#tokenDiv').text()).not.toBe(oldValues);
});

До сих пор я пытался переопределить функцию window.confirm, но тогда фактический вызов жалуется, что это undefined.

Я также хотел настроить шпиона Jasmine на window.confirm, но в следующем синтаксисе spyOn(window, 'confirm'); он дает мне сообщение о том, что вы не можете следить за null.

Как я могу сделать такую ​​пробную работу?

4b9b3361

Ответ 1

Тестирование E2E

Проконсультируйтесь с этим проектом: https://github.com/katranci/Angular-E2E-Window-Dialog-Commands

Тестирование устройств

Если вы создаете сервис для диалоговых окон, вы можете высмеять эту службу в своем unit test, чтобы сделать ваш код тестируемым:

контроллер

function TokenController($scope, modalDialog) {
  $scope.token = 'sampleToken';

  $scope.newToken = function() {
    if (modalDialog.confirm("Are you sure you want to change the token?") == true) {
      $scope.token = 'modifiedToken';
    }
  };
}

услуга modalDialog

yourApp.factory('modalDialog', ['$window', function($window) {
    return {
        confirm: function(message) {
            return $window.confirm(message);
        }
    }
}]);

modalDialogMock

function modalDialogMock() {
    this.confirmResult;

    this.confirm = function() {
        return this.confirmResult;
    }

    this.confirmTrue = function() {
        this.confirmResult = true;
    }

    this.confirmFalse = function() {
        this.confirmResult = false;
    }
}

Test

var scope;
var modalDialog;

beforeEach(module('yourApp'));

beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    modalDialog = new modalDialogMock();
    var ctrl = $controller('TokenController', {$scope: scope, modalDialog: modalDialog});
}));

it('should be able to generate new token', function () {
   modalDialog.confirmTrue();

   scope.newToken();
   expect(scope.token).toBe('modifiedToken');
});

Ответ 2

Другим вариантом было бы непосредственно создать шпион и автоматически вернуть true:

//Jasmine 2.0
spyOn(window, 'confirm').and.callFake(function () {
     return true;
});

//Jasmine 1.3
spyOn(window, 'confirm').andCallFake(function () {
     return true;
});

Ответ 3

В модульных тестах вы можете высмеивать объект $window следующим образом:

Ваш тест:

beforeEach(function() {
    module('myAppName');

    inject(function($rootScope, $injector) {
        $controller = $injector.get('$controller');
        $scope = $rootScope.$new();
        var windowMock = { confirm: function(msg) { return true } }
        $controller('UsersCtrl', { $scope: $scope, $window: windowMock });
    });
});

Ваш контроллер:

myAppName.controller('UsersCtrl', function($scope, $window) {
    $scope.delete = function() {
        var answer = $window.confirm('Delete?');
        if (answer) {
             // doing something
        }
    }
});