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

时间:2016-09-26 14:02:28

标签: javascript angularjs promise ecmascript-6 ngmock

我有一个功能:

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
}

从Angular控制器调用createClub()的位置。我还没有写控制器,因为我坚持测试。我正在使用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'}

1 个答案:

答案 0 :(得分:0)

时间问题。您的$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返回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)
    }
    // ...

  })
}