【发布时间】:2014-10-14 15:51:49
【问题描述】:
我正在尝试对一个控制器进行单元测试,该控制器通过异步服务获取一些翻译后的字符串,但我在 Jasmine vs Promises 上遗漏了一些东西......
让我们从错误开始,即:
TypeError: 'undefined' is not an object (evaluating 'i18n.get('navigation').then')
测试用例
beforeEach(inject(function ($rootScope) {
scope = $rootScope.$new()
}))
it('should invoke the i18n service for translations', inject(function ($controller, i18n) {
spyOn(i18n, 'get')
var HeaderCtrl = $controller('HeaderCtrl', {
$scope: scope,
i18n: i18n
})
expect(i18n.get).toHaveBeenCalledWith('navigation')
}))
控制器
.controller('HeaderCtrl', function ($scope, i18n) {
// removing the '.then' part makes the test pass,
// which makes me almost sure that my missing is in the promise mamnagement
i18n.get('navigation').then(
function (data) {
$scope.strings = data
},
function (err) {
console.log(err)
})
异步服务
get: function (key) {
var deferred = $q.defer()
$http.get('locale/en.json')
.success(function (data) {
deferred.resolve(data[key])
})
.error(function (err, status) {
deferred.reject(err, status)
})
return deferred.promise
}
我也尝试添加一些 $http 嘲笑,但无济于事
使用 $http 模拟测试
beforeEach(inject(function ($rootScope, $httpBackend) {
scope = $rootScope.$new()
$httpBackend.whenGET('locale/en.json')
.respond(enStrings)
}))
it('should invoke the i18n service for translations', inject(function ($controller, i18n) {
spyOn(i18n, 'get')
var HeaderCtrl = $controller('HeaderCtrl', {
$scope: scope,
i18n: i18n
})
$httpBackend.flush()
expect(i18n.get).toHaveBeenCalledWith('navigation')
}))
【问题讨论】:
-
@PSL 不走运。同样的错误
标签: angularjs unit-testing asynchronous jasmine