1

When mocking using $httpBackend, How do I create the mock when I do not know exactly the type of data being returned. I want the http call to be on controller initialsation. One caveat is that it will be a json object being returned.

 (function () {
    'use strict';

    angular
        .module('app')
        .service('dataService', dataService);


    function dataService($http) {
        this.getMovies = getMovies;

        ////////////////

        function getMovies() {
            return $http.get('./src/app/movies/data.json')
                .then(function (response) {
                    return response.data
                })
        }
    };
})();

;

(function () {
    'use strict';

    angular.module('app')
        .controller('moviesController', moviesController);

    moviesController.$inject = ['dataService'];

function moviesController(dataService) {
    var vm = this

    vm.movies;

    vm.getMovies = getMovies;
    getMovies();

    function getMovies() { 
        return dataService.getMovies()
            .then(function (data) {
                return vm.movies = data.movies;
            });
    }
};
}());

;

describe('moviesController', function () {

    var $controller,
        moviesController,
        dataService,
        $httpBackend;

    beforeEach(angular.mock.module('app'));
    beforeEach(angular.mock.module('ui.router'));

    beforeEach(inject(function (_$controller_, _dataService_, _$httpBackend_) {
        $controller = _$controller_;
        dataService = _dataService_;
        $httpBackend = _$httpBackend_;

        moviesController = $controller('moviesController', { dataService: dataService });
    }))

    it('should be defined', function () {
        expect(moviesController).toBeDefined();
    });

it('should initialise with a call to dataService.getMovies()', function () {
    var url = "./src/app/movies/data.json";
    var movies = {};
    $httpBackend.expectGET(url).respond(200, movies);
    moviesController.getMovies();
    expect(moviesController.movies).toEqual(movies);
    $httpBackend.flush(); 

});

});

;

Expected undefined to equal Object({  }).

1 Answers1

0

You can set the return to be an object you define in the spec.

var response = {};
it('should initialise with a call to dataService.getMovies()', function () {
    $httpBackend.expectGET("./src/app/movies/data.json").respond(response);
    $httpBackend.flush();
});
dwbartz
  • 886
  • 10
  • 13
  • @user3788267 See the edit. You have an extra single quote at the end of your expectGET url. – dwbartz Aug 30 '16 at 22:40
  • Silly me. I've corrected that however i'm still seeing the same error. – user3788267 Aug 30 '16 at 22:51
  • I think that you want to leave off the status code when involved like that. See here for returning custom status code. http://stackoverflow.com/questions/23937505/angular-httpbackend-expectget-respond-with-409-status-custom-statustext – dwbartz Aug 30 '16 at 22:56