7

私のメインdescribeでは、次のものがあります。

beforeEach(inject(function(...) {
    var mockCookieService = {
        _cookies: {},
        get: function(key) {
            return this._cookies[key];
        },
        put: function(key, value) {
            this._cookies[key] = value;
        }
    }

   cookieService = mockCookieService;

   mainCtrl = $controller('MainCtrl', {
       ...
       $cookieStore: cookieService
   }
}

後で、Cookie が既に存在するかどうかをコントローラーがどのように認識するかをテストしたいので、次の記述をネストします。

describe('If the cookie already exists', function() {
    beforeEach(function() {
        cookieService.put('myUUID', 'TEST');
    });

    it('Should do not retrieve UUID from server', function() {
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

ただし、変更を加えると、cookieService作成中のコントローラーに永続化されません。私は間違ったアプローチを取っていますか?

ありがとう!

編集:テスト コードを更新しました。これが $cookieStore の使用方法です。

var app = angular.module('MyApp', ['UserService', 'ngCookies']);

app.controller('MainCtrl', function ($scope, UserService, $cookieStore) {
var uuid = $cookieStore.get('myUUID');

if (typeof uuid == 'undefined') {
    UserService.getNewUUID().$then(function(response) {
        uuid = response.data.uuid;
        $cookieStore.put('myUUID', uuid);
    });
}

});

4

1 に答える 1

1

単体テストでは、モック $cookieStore を作成し、本質的にその機能を再実装する必要はありません。Jasmine のspyOn関数を使用して、スパイ オブジェクトを作成し、値を返すことができます。

スタブ オブジェクトを作成する

var cookieStoreStub = {};

コントローラを作成する前にスパイ オブジェクトを設定する

spyOn(cookieStoreStub, 'get').and.returnValue('TEST'); //Valid syntax in Jasmine 2.0+. 1.3 uses andReturnValue()

mainCtrl = $controller('MainCtrl', {
 ... 
 $cookieStore: cookieStoreStub 
}

Cookie が使用可能なシナリオの単体テストを作成する

describe('If the cookie already exists', function() {
    it('Should not retrieve UUID from server', function() {
        console.log(cookieStore.get('myUUID')); //Returns TEST, regardless of 'key'
        expect(userService.getNewUUID).not.toHaveBeenCalled();
    });
});

注: 複数のシナリオをテストする場合は、コントローラーの作成をブロック内cookieStore.get()に移動することをお勧めします。これにより、describe ブロックに適した値を呼び出して返すことができます。beforeEach()describe()spyOn()

于 2015-08-06T13:52:11.963 に答える