私は機能を持っています:
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'}