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

How to spy on $window.confirm with Karma / Jasmine?

我正在使用 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.

我做错了什么?

您需要在被测系统上调用该方法之前创建间谍。我看不到你的设置函数,但你可能需要将你监视的控制器传递给 $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();
});