【发布时间】:2017-02-03 22:11:33
【问题描述】:
我有一个函数:
function validateClub(club) {
//.. other validation
let existingClub
$http.get('/clubs/fetch/' + club.clubName).then(data => {
existingClub = data
}, err => {
$log.error(err)
})
console.log(existingClub)
if(existingClub) return {result: false, reason: 'Club already exists. Choose another Club Name'}
return {result: true}
}
我这样称呼它:
function createClub(club) {
let validationResult = validateClub(club)
console.log(validationResult)
if (validationResult.result === false) {
throw new Error('The Club you entered has failed validation reason: ' + validationResult.reason)
}
// .. create club logic
}
createClub() 是从 Angular 控制器调用的。我还没有编写控制器,因为我被测试困住了。我正在使用 ngMocks $httpBackend 来伪造响应,如下所示:
describe.only('when creating a new club with an existing clubName', () => {
it('should throw exception', () => {
$httpBackend
.when('GET', '/clubs/fetch/ClubFoo')
.respond(200, {_id:'1', clubName: 'ClubFoo', owner: 'foo@bar.com'})
const newClub = {
clubName: 'ClubFoo',
owner: 'foo@bar.com',
}
dataService.createClub(newClub).then(data => {
response = data
})
$httpBackend.flush()
// expect(fn).to.throw('The Club Name you have entered already exists')
// ignore the expect for now, I have changed the code for Stack Overflow
})
})
console.log(existingClub) 始终为 undefined
console.log(validationResult) 始终是 {result: true}
我做错了什么?我希望前者是{_id:'1', clubName: 'ClubFoo', owner: 'foo@bar.com'},后者是{result: false, reason: 'Club already exists. Choose another Club Name'}
【问题讨论】:
-
$http.get 返回一个承诺,不是吗?它可能还没有解决 - 当你做小控制台.log时。
-
是的。但是如果我在
then中执行console.log 就会解决...对吗?我试过了。 -
为了解决您正在创建的承诺,您必须在测试用例中注入一个范围/或(根范围)并使用范围启动下一个摘要周期。$digest()
-
我可以使用 $q 服务吗?我试过了,但我有一个想法
-
该死,不好。你有关于将范围注入测试的任何信息吗?我会调查一下
标签: javascript angularjs promise ecmascript-6 ngmock