设置:Karma,Browserify,Jasmine,Angular。
我正在尝试测试一个Angular服务,而该服务又使用了另一个我想模拟的服务。
我感觉在这里我得到了另一个我的ItemLocalStorageService实例,它是在模拟注入发生之前创建的。
ItemLocalStorageService.js
'use strict';
var _ = require('underscore'),
LOCALSTORAGE_LIST_KEY = 'items.list',
items;
module.exports = [
'StoreService',
function (StoreService) {
var getAll = function () {
if (StoreService.enabled) {
items = StoreService.get(LOCALSTORAGE_LIST_KEY);
}
return items;
};
var saveAll = function (latestItems) {
if (StoreService.enabled) {
StoreService.set(LOCALSTORAGE_LIST_KEY, latestItems);
}
items = latestItems;
};
return {
getAll: getAll,
saveAll: saveAll
};
}
];
ItemLocalStorageServiceTest.js
// Main application file. This is loaded here
// instead of being added to Karma's files array
// because of the Browserify setup.
require('scripts/app');
var mock = require('angular').mock;
describe('ItemLocalStorageService', function () {
var ItemLocalStorageService,
items,
mockStoreService;
beforeEach(mock.module('myApp'));
beforeEach(mock.module('myTemplates'));
beforeEach(function () {
items = [ {}, {}, {} ];
mockStoreService = {
'store': {
enabled: false,
get: jasmine.createSpy('store.get').and.returnValue(items),
set: jasmine.createSpy('store.set')
}
};
// Either of these two should work, I believe.
// 1
// mock.module({ 'StoreService': mockStoreService })''
// 2
mock.module(function($provide) {
$provide.value('StoreService', mockStoreService);
});
});
describe('Local storage', function () {
it('should return items from local storage', function () {
mock.inject(function (_ItemLocalStorageService_) {
ItemLocalStorageService = _ItemLocalStorageService_;
});
expect(ItemLocalStorageService.getAll()).toEqual(items);
expect(mockStoreService.store.get).toHaveBeenCalled();
});
});
});
两个期望都失败了。 getAll
的输出是浏览器本地存储的实际内容,而不是我提供的模拟输出。我显然做错了什么,所以我很乐意接受任何指示,以正确的方式引导我。