我花了很多時間試圖瞭解$ httpBackend和angular-translate如何協同工作以測試翻譯功能是否仍然有效。
我在這一點上,我真的不知道如何解決這個問題。
'use strict';
describe('Directive: translate', function() {
beforeEach(function() {
angular.module('myApp', ['pascalprecht.translate']);
});
var element,
$compile,
$rootScope,
$http,
$httpBackend;
beforeEach(inject(function (_$rootScope_, _$compile_, _$httpBackend_, _$http_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$http = _$http_;
$httpBackend = _$httpBackend_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should translate to English', function() {
element = $compile('<p translate>discover_more</p>')($rootScope);
$rootScope.$digest();
$httpBackend.expect('GET', 'langs/en.json').respond(200); // Should I return some data at this point?
$http.get('langs/en.json').then(function() {}); // Should I do something here?
$httpBackend.flush();
expect(element.html()).toBe('Discover more');
});
});
我的測試當然失敗了。問題是我不知道如何1)真正獲得JSON的數據,2)說這個指令「這裏是你的數據,做你的工作」。
編輯:
好的,一些問題。我只是看着這個角度模塊(https://github.com/angular-translate/angular-translate/tree/master/test/unit/directive)的測試,我可以讓它工作:
'use strict';
describe('Directive: translate', function() {
beforeEach(function() {
angular.module('gajoApp', ['pascalprecht.translate']);
});
var element,
$compile,
$rootScope;
beforeEach(module('pascalprecht.translate', function ($translateProvider) {
$translateProvider
.translations('en', {
'discover_more': 'Discover more'
})
.preferredLanguage('en');
}));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('should translate to English', function() {
element = $compile('<p translate>discover_more</p>')($rootScope);
$rootScope.$digest();
expect(element.html()).toBe('Discover more');
});
});
我想什麼,但是,是結合了返回的JSON正確的AJAX調用此解決方案,測試這一切也已完成。
我已經認爲沒有明確的$ http請求必須存在,但事實上,當我不這樣做時,我得到錯誤「沒有待處理的請求刷新!」。我已經嘗試過你的解決方案,但沒有成功:/角度翻譯似乎需要別的東西才能正常運行......但我不知道那會是什麼。無論如何,謝謝你的嘗試,丹尼爾。 – DanielM 2014-09-02 20:37:19
嘗試提供更多信息...實際上,需要通過$ translatorProvider進行一些配置(設置前綴和首選語言)。是否有必要爲測試配置這些東西,或者應用程序配置是否得到了某種程度?如果是這樣,我怎麼能從測試內部調用.config()?另一件事是,如果我嘗試在beforEach()中注入$ translate(可以替代第一個配置),就像我在控制器中使用它一樣,我會收到錯誤「Unknown provider:$ translateProvider」 。 – DanielM 2014-09-02 21:04:05