如何使用 jasmine 和 angularjs 测试我的服务 returns 数据

How to test that my service returns data with jasmine and angularjs

我已经开始使用 jasmine 来测试我在 angularjs 中的控制器,但是在阅读了一些教程之后我有点卡住了。

我有一个名为 jasmineController

的简单 angularjs 控制器
(function () {
    "use strict";

    var myAppModule = angular.module('myApp');

    myAppModule.controller('jasmineController', ['$scope', 'genericService',
        function ($scope, genericService) {
            $scope.name = 'Superhero';
            $scope.counter = 0;
            $scope.$watch('name', function (newValue, oldValue) {
                $scope.counter = $scope.counter + 1;
            });

            $scope.testPromise = function() {
                return genericService.getAll("dashboard", "currentnews", null, null, null);
            }

            $scope.getNewsItems = function () {
                genericService.getAll("dashboard", "currentnews", null, null, null).then(function (data) {

                    $scope.name = 'Superhero';
                    $scope.newsItems = data;

                });
            }

        }
    ]);
})();

在我的 jasmine 测试中,我想调用 getNewsItems 并检查它是否可以调用 genericService.getAll 并且为 $scope.newsItems 分配了一些数据。我知道我会模拟该服务,但实际上我不会调用它。

这是我的规格

describe("test", function () {
    // Declare some variables required for my test
    var controller, scope, genericService;

    // load in module
    beforeEach(module("myApp"));


    beforeEach(inject(function ($rootScope, $controller, _genericService_) {
        genericService = _genericService_;
        // assign new scope to variable
        scope = $rootScope.$new();
        controller = $controller('jasmineController', {
            '$scope': scope
        });
    }));
    it('sets the name', function () {
        expect(scope.name).toBe('Superhero');
    });

    it('should assign data to scope', function() {
        //var fakeHttpPromise = {success: function () { }};
        scope.getNewsItems();
        spyOn(genericService, 'getAll');
        expect(genericService.getAll).toHaveBeenCalledWith('dashboard', 'currentnews');
    });

});

我有一个用于 genericService.getall() 的 spyon,但除此之外,我有点坚持检查我的范围变量是否被赋值。

我也得到了这个堆栈跟踪:

Error: Expected spy getAll to have been called with [ 'dashboard', 'currentnews' ] but it was never called.
   at stack (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1441:11)
   at buildExpectationResult (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1408:5)
   at expectationResultFactory (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:533:11)
   at Spec.prototype.addExpectationResult (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:293:5)
   at addExpectationResult (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:477:9)
   at Anonymous function (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1365:7)
   at Anonymous function (file:///C:/Projects/2013/AMT2015/AMT2015.WebAPP/Scripts/tests/controllers/dashboardControllerSpec.js:49:9)
   at attemptSync (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1759:9)
   at QueueRunner.prototype.run (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1747:9)
   at QueueRunner.prototype.execute (file:///C:/Users/nickgowdy/Local%20Settings/Application%20Data/Microsoft/VisualStudio/12.0/Extensions/4sg2jkkc.gb4/TestFiles/jasmine/v2/jasmine.js:1733:5)

在调用测试函数之前,您需要先放置间谍。而你实际上是在将更多参数传递给服务功能。因此,您需要使用确切的参数列表进行测试。

it('should assign data to scope', function() {
        //var fakeHttpPromise = {success: function () { }};
        spyOn(genericService, 'getAll');
        scope.getNewsItems();
        expect(genericService.getAll).toHaveBeenCalledWith('dashboard', 'currentnews',null,null,null);
    });

我最终这样做了:

describe("test", function () {
    // Declare some variables required for my test
    var controller, scope, genericService;

    // load in module
    beforeEach(module("myApp"));


    beforeEach(inject(function ($rootScope, $controller, _$q_, _genericService_) {
        genericService = _genericService_;
        var deferred = _$q_.defer();
        deferred.resolve('resolveData');
        spyOn(genericService, 'getAll').and.returnValue(deferred.promise);

        scope = $rootScope.$new();
        controller = $controller('jasmineController', {
            '$scope': scope
        });
    }));
    it('sets the name', function () {
        expect(scope.name).toBe('Superhero');
    });

    it('should assign data to scope', function() {
        //spyOn(genericService, 'getAll').and.callFake(function() {

        //});
        scope.getNewsItems();
        scope.$apply();
        expect(scope.newsItems).toBe('resolveData');
        //expect(genericService.getAll).toHaveBeenCalledWith('dashboard', 'currentnews', null, null, null);

    });

});

因为我的测试不仅仅是调用服务,还要处理承诺,所以我不得不注入 $q。然后监视我说要调用服务和方法,return 值是延迟的承诺。

最后,我可以查看作用域变量,看看是否为这一行分配了任何内容:

expect(scope.newsItems).toBe('resolveData');

感谢所有帮助过的人。