无法从模拟 $httpBackend 服务获得正确的结果

Cannot get correct result from mock $httpBackend service

我有一个函数:

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 请求没有立即得到解决。 (即 existingClubundefinedvalidateClub 总是 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 return 承诺 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)
    }
    // ...

  })
}