无法从mock $httpBackend服务中获得正确的结果



我有一个函数:

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)总是undefinedconsole.log(validationResult)总是{result: true}

我做错了什么?我希望前者是{_id:'1', clubName: 'ClubFoo', owner: 'foo@bar.com'},后者是{result: false, reason: 'Club already exists. Choose another Club Name'}

这只是时间问题。您的$http请求没有立即解决。(即existingClubundefined, 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)
    }
    // ...
  })
}

相关内容

  • 没有找到相关文章

最新更新