使用Angular模拟Cookies

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);
    });
}

});


你能展示一下在你的控制器中如何使用 $cookieStore 吗?以及你如何测试这个控制器? - Ye Liu
更新了,如果需要更多的测试代码,请告诉我。 - grivescorbett
“it's not persisting into the controller”是什么意思?你是想说你的控制器没有使用模拟数据吗?还是当你调用$cookieStore.get()时,无法得到预期的值? - Ye Liu
如果我在嵌套的描述块的beforeEach中调用cookieService.put(...),那么当我在控制器内记录$cookieStore.get(...)时,它会返回未定义,就好像它看不到我试图模拟的cookie。 - grivescorbett
我明白了。确保控制器实际上调用了模拟对象的方法。如果可以的话,尝试创建一个 plunk 或 fiddle,这将非常有帮助。 - Ye Liu
1个回答

1
你的单元测试不必创建一个模拟的 $cookieStore 并且基本上重新实现其功能。你可以使用 Jasmine 的 spyOn 函数来创建一个 spy 对象并返回值。
创建一个存根对象。
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()中。这样可以让您调用spyOn()并返回适合描述块的值。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接