我試圖測試一個Angular服務,我知道它在功能上已經適用了一段時間。我剛來複古適合現在的一些測試,但我收到了一些奇怪的問題,我收到一條消息,「必須從茉莉花測試中返回$ get factory method的值」。
服務做工作,在網站和服務將返回一個API
var service = {
setStartLanguage: setStartLanguage,
setLanguage: setLanguage,
supportedLanguages: supportedLanguages,
currentLanguage: etCurrentLanguage.currentLanguage,
getLanguage: getLanguage
};
return service;
我相信這是足以讓它工作,但我無法弄清楚,爲什麼測試抱怨它沒有返回$得到。
哦,我爲測試所做的一切都試圖預期服務已定義。
編輯: 全方位服務代碼,
(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;
}
}());
你能分享進一步的代碼來說明你是如何準確地使用你的控制器此服務等?這是您自己編寫的服務,我假設(不是內置的Angular?) – mindparse
您能告訴我們您的測試代碼嗎? –