如何使用Karma / Jasmine监视$ window.confirm?

时间:2015-05-08 18:37:35

标签: angularjs unit-testing jasmine karma-runner

我正在使用Angular,我的控制器有:

        clearCustom: function () {
            // make sure they are doing this on purpose
            if (!$window.confirm('Are you sure you want to delete this phone number?')) return;

            if ($scope.model.originalPhoneSms === $scope.model.phoneCustom) {
                $scope.model.patient.phoneSms = '';
                $scope.model.patient.phoneSmsVerified = false;
                $scope.model.originalPhoneSms = '';
                cache.set('patient', 'currentPatient', $scope.model.patient);
            }
            $scope.model.phoneCustom = '';
            $scope.save();
        }

我的测试是:

it('should confirm that the user is trying to clear the custom phone number', function() {
    scope.clearCustom();

    var windowMock = jasmine.createSpyObj('$window', ['confirm']);

    expect(windowMock.confirm).toHaveBeenCalled();
});

但它失败了Expected spy $window.confirm to have been called.

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要在调用被测系统上的方法之前创建间谍。我无法看到您的设置功能,但您可能需要传递您在$window对象上监视的控制器。

var $window;

beforeEach(inject([$controller, function ($controller) {
    $window = jasmine.createSpyObj('$window', ['confirm']);

    $controller('your.module.controller.foo', {
        $window: $window
    });
}]));

it('should confirm that the user is trying to clear the custom phone number', function() {
    scope.clearCustom();

    expect($window.confirm).toHaveBeenCalled();
});