我正在尝试测试一个Angular服务,我知道它在功能上已经存在了一段时间。我现在只是来复古一些测试,但我得到一个奇怪的问题,我得到一个消息"必须从$ get factory方法返回一个值"来自茉莉花测试。
该服务在网站中有效,服务返回API
var service = {
setStartLanguage: setStartLanguage,
setLanguage: setLanguage,
supportedLanguages: supportedLanguages,
currentLanguage: etCurrentLanguage.currentLanguage,
getLanguage: getLanguage
};
return service;
我相信这足以让它发挥作用,但我无法弄清楚为什么测试会抱怨它没有返回$ get。
哦,我为测试所做的一切都是试图期望定义服务。
编辑: 完整的服务代码,
(function () {
'use strict';
angular.module('app.core').factory('etLanguageService', ['$translate', '$route', 'etCurrentLanguage', 'supportedLanguages', 'localStorageService', etLanguageService]);
function etLanguageService($translate, $route, etCurrentLanguage, supportedLanguages, localStorageService) {
function setLanugageFromLocalStorage(storedLanguage) {
etCurrentLanguage.currentLanguage = storedLanguage;
$translate.preferredLanguage(etCurrentLanguage.currentLanguage.code);
localStorageService.set('currentLanguage', etCurrentLanguage.currentLanguage);
}
function setLanguageFromBrowser() {
var language = etCurrentLanguage.get();
if (!language) {
language = '';
}
var cleanLanguage = language.substr(0, 2).toLowerCase();
var supportedLanguage = _.find(supportedLanguages, function(language) {
return language.code === cleanLanguage;
});
$translate.preferredLanguage(supportedLanguage.code);
localStorageService.set('currentLanguage', supportedLanguage);
}
function setStartLanguage() {
// first check if we have a stored language
var storedLanguage = localStorageService.get('currentLanguage');
if (storedLanguage) {
setLanugageFromLocalStorage(storedLanguage);
} else {
setLanguageFromBrowser();
}
}
function setLanguage(language) {
if (etCurrentLanguage.currentLanguage !== language) {
etCurrentLanguage.currentLanguage = language;
$translate.use(etCurrentLanguage.currentLanguage.code).then(function () {
localStorageService.set('currentLanguage', etCurrentLanguage.currentLanguage);
$route.reload();
});
}
}
function getLanguage() {
return localStorageService.get('currentLanguage');
}
var service = {
setStartLanguage: setStartLanguage,
setLanguage: setLanguage,
supportedLanguages: supportedLanguages,
currentLanguage: etCurrentLanguage.currentLanguage,
getLanguage: getLanguage
};
return service;
}
}());
答案 0 :(得分:0)
如果没有更多的测试代码,那很难说清楚。
$get
是您服务提供商提供的方法。对于每个服务,都有一个提供者负责通过$get
方法创建服务实例。如果您有一项名为myService
的服务,则会有一个提供商myServiceProvider
。 Internaly,当引导您的应用时,Angular会调用mysServiceProvider.$get
来获取您的服务实例。
如果您正在修补提供商和模拟提供商,那可能是一个原因......