Loading a mock JSON file within Karma+AngularJS test

前端 未结 8 1549
星月不相逢
星月不相逢 2020-11-28 18:57

I have an AngularJS app set up with tests using Karma+Jasmine. I have a function I want to test that takes a large JSON object, converts it to a format that\'s more consumab

8条回答
  •  粉色の甜心
    2020-11-28 19:13

    Here is an alternative to Cameron's answer, without the need for jasmine-jquery nor any extra Karma config, to test e.g. an Angular service using $resource :

    angular.module('myApp').factory('MyService', function ($resource) {
        var Service = $resource('/:user/resultset');
        return {
            getResultSet: function (user) {
                return Service.get({user: user}).$promise;
            }
        };
    });
    

    And the corresponding unit test :

    describe('MyServiceTest', function(){
        var $httpBackend, MyService, testResultSet, otherTestData ;
    
        beforeEach(function (done) {
            module('myApp');
            inject(function ($injector) {
                $httpBackend = $injector.get('$httpBackend');
                MyService = $injector.get('MyService');
            });
            // Loading fixtures
            $.when(
                $.getJSON('base/test/mock/test_resultset.json', function (data) { testResultSet = data; }),
                $.getJSON('base/test/mock/test_other_data.json', function (data) { otherTestData = data; })
            ).then(done);
        });
    
        it('should have some resultset', function() {
            $httpBackend.expectGET('/blahblahurl/resultset').respond(testResultSet);
            MyService.getResultSet('blahblahurl').then(function (resultSet) {
                expect(resultSet.length).toBe(59);
            });
            $httpBackend.flush();
        });
    });
    

提交回复
热议问题