【问题标题】:Spying not working with Angular, Jasmine and Sinon间谍不能与 Angular、Jasmine 和 Sinon 一起工作
【发布时间】:2015-08-14 08:55:23
【问题描述】:

我试图监视控制器中定义的方法,但无论我做什么,我都会看到测试失败并显示以下消息:

错误:预期是间谍,但得到了函数。

我将 Karma、Jasmine 和 Sinon 与 Angular 一起使用。我很确定一切设置正确,因为只从 $scope 读取属性的测试通过了。

例如,我有一个非常简单的应用模块:

angular.module('app', []);

还有这个非常简单的控制器:

angular.module('app').controller('myController', ['$scope', function($scope) {
    $scope.test = '';
    $scope.setTest = function (newString) {
        $scope.test = newString || 'default';
    }
    $scope.updateTest = function (newString) {
        $scope.setTest(newString);
    };
}]);

我的spec文件如下:

describe('myController', function () {
    'use strict';

    beforeEach(module('app'));

    var $scope, sandbox;

    beforeEach(inject(function ($controller) {
        $scope = {};
        $controller('myController', { $scope: $scope });

        sandbox = sinon.sandbox.create();
    }));

    afterEach(function () {
        sandbox.restore();
    });

    describe('#updateTest()', function () {

        beforeEach(function () {
            sandbox.spy($scope, 'setTest');
        });

        it('updates the test property with a default value', function () {
            $scope.updateTest();

            expect($scope.test).toEqual('default');
        });

        it('calls the setTest method', function () {
            $scope.updateTest();

            expect($scope.setTest).toHaveBeenCalled();

        });

    });
});

第一个测试(它只是检查测试属性是否更新)通过。

第二个测试,我只想监视 setTest() 方法,失败并显示上面的错误消息。

如果我在beforeEach 中注销$scope,我可以看到setTest 方法并且没有脚本错误。

我错过了什么?

【问题讨论】:

    标签: angularjs jasmine sinon


    【解决方案1】:

    我猜这是因为你正在混合 Jasmine 和 Sinon,我不认为 Sinon 间谍 sandbox.spy() 会与 Jasmine matcher expect().toHaveBeenCalled() 一起工作。您应该选择使用哪一个:

    1. 使用Sinon spies并将结果转换为原始数据以将其传递给Jasmine:

      sandbox.spy($scope, 'setTest');
      expect($scope.setTest.called).toBeTruthy();
      

      但是这种方法会给你更少的冗长输出:Expected true to be false,而不是通常的Expected spy to have been called

    2. 使用 Jasmine 间谍:

      spyOn($scope, 'setTest');
      expect($scope.setTest).toHaveBeenCalled();
      

    您还可以查看jasmine-sinon 工具,它添加了额外的 Jasmine 匹配器并允许将 Sinon 间谍与 Jasmine 间谍匹配器一起使用。因此,您应该可以在示例中使用 like:

    sandbox.spy($scope, 'setTest');
    expect($scope.setTest).toHaveBeenCalled();
    

    【讨论】:

    • 太棒了,我忘了这个包!我将安装它并尝试使其正常工作。我之前在上面的示例中使用过 Karma/Jasmine/Sinon,但我根本没有参与设置....
    • 是的,就是这样,谢谢先生!我还必须通过将文件添加到 Karma 加载的文件列表中来加载 Karma 中的文件。
    猜你喜欢
    • 2018-12-26
    • 2018-08-16
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多