Loading a mock JSON file within Karma+AngularJS test

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

    looks like your solution is the right one but there are 2 things i don't like about it:

    • it uses jasmine
    • it requires new learning curve

    i just ran into this problem and had to resolve it quickly as i had no time left for the deadline, and i did the following

    my json resource was huge, and i couldn't copy paste it into the test so i had to keep it a separate file - but i decided to keep it as javascript rather than json, and then i simply did:

    var someUniqueName = ... the json ...

    and i included this into karma conf includes..

    i can still mock a backend http response if needed with it.

    $httpBackend.whenGET('/some/path').respond(someUniqueName);

    i could also write a new angular module to be included here and then change the json resource to be something like

    angular.module('hugeJsonResource', []).constant('SomeUniqueName', ... the json ... );

    and then simply inject SomeUniqueName into the test, which looks cleaner.

    perhaps even wrap it in a service

    angular.module('allTestResources',[]).service('AllTestResources', function AllTestResources( SomeUniqueName , SomeOtherUniqueName, ... ){
       this.resource1 = SomeUniqueName;
       this.resource2 = SomeOtherUniqueName; 
    })
    

    this solutions was faster to me, just as clean, and did not require any new learning curve. so i prefer this one.

提交回复
热议问题