Loading a mock JSON file within Karma+AngularJS test

前端 未结 8 1580
星月不相逢
星月不相逢 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:35

    I've been struggling to find a solution to loading external data into my testcases. The above link: http://dailyjs.com/2013/05/16/angularjs-5/ Worked for me.

    Some notes:

    "defaultJSON" needs to be used as the key in your mock data file, this is fine, as you can just refer to defaultJSON.

    mockedDashboardJSON.js:

    'use strict'
    angular.module('mockedDashboardJSON',[])
    .value('defaultJSON',{
        fakeData1:{'really':'fake2'},
        fakeData2:{'history':'faked'}
    });
    

    Then in your test file:

    beforeEach(module('yourApp','mockedDashboardJSON'));
    var YourControlNameCtrl, scope, $httpBackend, mockedDashboardJSON;
    beforeEach(function(_$httpBackend_,defaultJSON){
        $httpBackend.when('GET','yourAPI/call/here').respond(defaultJSON.fakeData1);
        //Your controller setup 
        ....
    });
    
    it('should test my fake stuff',function(){
        $httpBackend.flush();
        //your test expectation stuff here
        ....
    }
    

提交回复
热议问题