Read more

Jasmine: Mocking API requests in an Angular service spec

Dominik Schöler
November 08, 2017Software engineer at makandra GmbH

Situation: You want to write a spec for a function inside an Angular service. This function at some point makes an API request and acts upon response. Notably, your Angular app employs uiRouter, although it is not used nor actually required for this test.

Working test setup

# Capitalized expressions are intended to be replaced with YOUR values

describe 'SERVICE', ->

  beforeEach ->
    module 'MODULE'

    module ($urlRouterProvider) ->
      # Prevent uiRouter's initialization, i.e. do not sync the current URL
      # with its routes
      $urlRouterProvider.deferIntercept()

    inject (_$httpBackend_, _SERVICE_) =>
      @$httpBackend = _$httpBackend_
      @SERVICE = _SERVICE_

  afterEach ->
    @$httpBackend.verifyNoOutstandingExpectation()
    @$httpBackend.verifyNoOutstandingRequest()

  describe 'FUNCTION()', ->
    it 'does something', ->
      # Maybe some code here
      
      # Call function under test (triggers API request, which will be intercepted)
      @SERVICE.FUNCTION()
      
      # ... do something before request is answered
      
      # Set up request expectation
      @$httpBackend.expectGET('/api/something').respond
        nested:
          example: 'json'
      
      # Run all queued requests
      @$httpBackend.flush()
      
      # Have a Jasmine expectation
      expect(something).toHaveHappened()

Notes

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot
Dominik Schöler
November 08, 2017Software engineer at makandra GmbH
Posted by Dominik Schöler to makandra dev (2017-11-08 11:46)