Search code examples
javascriptangularjspromiseecmascript-6angularjs-ngmock

Cannot get correct result from mock $httpBackend service


I have a function:

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}
}

and I call it like this:

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
}

Where createClub() is called from an Angular controller. I haven't got to writing the controller yet as I'm stuck with the test. I am using ngMocks $httpBackend to fake a response, like this:

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: '[email protected]'})

    const newClub = {
      clubName: 'ClubFoo',
      owner: '[email protected]',
    }

    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) is always undefined console.log(validationResult) is always {result: true}

What am I doing wrong? I'm expecting the former to be {_id:'1', clubName: 'ClubFoo', owner: '[email protected]'} and the latter to be {result: false, reason: 'Club already exists. Choose another Club Name'}


Solution

  • It's matter of timing. your $http request doesn't resolved immediately. (i.e. existingClub are undefined and validateClub always 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)
      })
    }
    

    also should createClub return promise for 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)
        }
        // ...
    
      })
    }