如何对Angular服务与$ cookies的交互进行单元测试?

Jer*_*oen 5 cookies unit-testing angularjs angularjs-service karma-runner

我目前有一项服务,取决于$ cookies中设置的变量.但是,当我想要对服务和$ cookies中存储的值之间的交互进行单元测试时,则在实际初始化$ cookie值之前始终初始化服务.

所以,我的问题是:如何正确地测试服务和$ cookie值之间的交互?(例如:如何在我的服务初始化之前设置$ cookies中的值?)

注意:我使用Angular 1.2和Karma进行单元测试.

Eit*_*eer 6

我在JSFiddle中创建了一个示例,希望能帮助您解决问题.

链接

//--- CODE --------------------------
angular.module('myapp.test', [], function () {

}).controller('testcont', function($scope, $cookies) {
    // Read a cookie and do something with it
    $scope.favoriteCookie = $cookies.myFavorite;
});

// --- SPECS -------------------------

describe('controllers', function(){
  var scope;   
  beforeEach(angular.mock.module('ngCookies', 'myapp.test'));   
  beforeEach(inject(function($controller, $rootScope, $cookies){    
    // Setting a cookie for testing
    $cookies.myFavorite = 'oatmeal';
    scope = $rootScope.$new();
      $controller('testcont', {$scope:scope, $cookies: $cookies});
  }));

  it('sets the cookie on the scope', function(){
      expect(scope.favoriteCookie).toBe('oatmeal');      
  });
});
Run Code Online (Sandbox Code Playgroud)


小智 2

我发现与服务(而不是控制器)一起使用的唯一方法是$cookieStorebeforeEach.

anagular-mocks 让我们以与在代码中类似的方式在规范中配置模块,不同之处在于config我们不使用函数,而是将函数作为第二个参数传递给module用于在 jasmine 中调用模块的函数。

它看起来像这样:

describe ('my service', function () {
    var $cookieStore,
        myService

    beforeEach(module ('myModule', function ($provide) {
        // this function configures the "myModule" module before any
        // injectables are created.

        // We use a decorator to access the cookie store before other
        // services are instantiated.
        $provide.decorator ('$cookieStore', function ($delegate) {
            // at this point the "$cookieStore" service  has only just 
            // been constructed, and is accessible here as "$delegate".
            // Services that have "$cookieStore" as an injected
            // dependency have not been instantiated yet, so we
            // can slip our cookie in now.
            $delegate.put ('favorite-cookie', 'oatmeal');
            return $delegate;
        });
    }));

    beforeEach (inject (function (_$cookieStore_, _myService_) {
        myService = _myService;
        $cookieStore = _$cookieStore_;
    }

    it ('should interact with the pre-existing "favorite-cookie" cookie', function () {
        // your expectations go here.
    });

    afterEach(function() {
        // clean up
        $cookieStore.remove ('favorite-cookie');
    });


});
Run Code Online (Sandbox Code Playgroud)