我花了很多时间试图理解$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)说“这是你的数据,做你的工作”的指令。
编辑:
好的,在这个问题上有一些亮点。我只是在看这个angular模块(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调用结合起来,以测试是否也执行了此操作。
发布于 2014-09-03 03:08:44
无论angular-translate需要什么,您都应该从预期的GET请求中返回,以实际替换元素中的discover_more。
beforeEach(function () {
$httpBackend.when(
'GET',
'langs/en.json'
).respond({'discover_more': 'Discover more'});
}); 请注意,我不知道angular-translate所期望的excact对象,因此它可能与我的建议不同。无论如何,当GET请求被感知时,返回它。
此外,您不应该在测试中自己发出GET请求。如果一切都设置正确,如果您将预期的返回添加到预期的GET请求中,那么它应该可以工作。
发布于 2015-09-05 12:17:39
不幸的是,这是由于restrictions on angular-translate造成的,但您可以通过以下两种方式使用真正的JSON locale文件:
1)在angular-translate请求区域设置文件时,使用load JSON files与$httpBackend相结合的插件加载区域设置文件。
beforeEach(inject(function (_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('locale-pt.json').respond(readJSON('langs/en.json'));
$httpBackend.flush();
})));2)用插件读取的$translateProvider.translations()方法覆盖应用程序的翻译,以加载JSON文件
beforeEach(module(function ($translateProvider) {
$translateProvider.translations('en', readJSON('langs/en.json'));
}));注意这应该在你的beforeEach(module('myApp'));下面,否则你会得到一个$injector错误。
https://stackoverflow.com/questions/25558597
复制相似问题