我有一个函数:
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
请求没有立即解决。(即existingClub
是undefined
, validateClub
总是return {result: true}
)。
function validateClub(club) {
let existingClub
// make fn return promise
return $http.get('/clubs/fetch/' + club.clubName).then(data => {
// update existingClub info when $http req resolved
existingClub = data
console.log(existingClub)
if(existingClub) return {result: false, reason: '...'}
return {result: true}
}, err => {
$log.error(err)
})
}
createClub
也应该返回dataService.createClub(newClub).then(...)
的承诺
function createClub(club) {
return validateClub(club).then(validationResult => {
console.log(validationResult)
if (validationResult.result === false) {
throw new Error('The Club you entered has failed validation reason: ' + validationResult.reason)
}
// ...
})
}