我可以使用Jasmine间谍为AngularJS服务编写测试用例吗?

时间:2013-08-02 09:04:03

标签: unit-testing angularjs jasmine

我正在使用AngularJS构建应用程序,我现在正在为我的应用程序开发测试用例。假设我有这样的服务;

var app = angular.module('MyApp')
app.factory('SessionService', function () {

    return {
        get: function (key) {
            return sessionStorage.getItem(key);
        },
        set: function (key, val) {
            return sessionStorage.setItem(key, val);
        },
        unset: function (key) {
            return sessionStorage.removeItem(key);
        }
    };
});

我可以为我的服务编写测试用例吗?

beforeEach(module('MyApp'));
    describe('Testing Service : SessionService', function (SessionService) {
        var session, fetchedSession, removeSession, setSession;
        beforeEach(function () {
            SessionService = {
                get: function (key) {
                    return sessionStorage.getItem(key);
                },
                set: function (key, val) {
                    return sessionStorage.setItem(key, val);
                },
                unset: function (key) {
                    return sessionStorage.removeItem(key);
                }
            };
            spyOn(SessionService, 'get').andCallThrough();
            spyOn(SessionService, 'set').andCallThrough();
            spyOn(SessionService, 'unset').andCallThrough();
            setSession     = SessionService.set('authenticated', true);
            fetchedSession = SessionService.get('authenticated');
            removeSession  = SessionService.unset('authenticated');
        });
        describe('SessionService', function () {
            it('tracks that the spy was called', function () {
                expect(SessionService.get).toHaveBeenCalled();
            });
            it('tracks all the arguments used to call the get function', function () {
                expect(SessionService.get).toHaveBeenCalledWith('authenticated');
            });
            //Rest of the Test Cases
        });
    });

我正在使用Jasmine的间谍方法开发此测试用例。这样很好还是我错了?

1 个答案:

答案 0 :(得分:1)

看起来不错。但我认为你会遇到一些问题:

get: function (key) {
        return sessionStorage.getItem(key);
},

你没有嘲笑sessionStorage。所以我想你在尝试从这个对象调用getItem()时会出错。看来你对测试中这些调用的返回值不感兴趣。您只检查是否使用正确的属性调用它们。像这里:

it('tracks that the spy was called', function () {
   expect(SessionService.get).toHaveBeenCalled();
});

为什么不更改SessionService的模拟以返回任何内容?像这样:

get: function (key) {
        return true;
},

如果你想测试你的getItem / setItem / removeItem,你可以在另一个测试用例中做到这一点

相关问题