dvdpzzt
dvdpzzt

Reputation: 73

Make module load JSON Karma AngularJS

I have a project built in AngularJS and I want to add unit test using Jasmine and Karma. Everytime I try to run a test I get 'Failed to instantiate module' because in the source code I load a local json file using XMLHttpRequest but in the test the same function respond with a 404. The json is a configuration file so if it's not loaded all the app can not be loaded properly. I tried with $httpBackend to capture the GET request and answer with a custom json but seems that $httpBackend cannot capture the request.

EDIT

I think the problem is the same of this

Upvotes: 0

Views: 92

Answers (1)

nircraft
nircraft

Reputation: 8478

You can use mock data from JSON file by picking it up using require() function:

const data: any = require('../../assets/sample-data.json');

Now you should be able to use data object in your tests. Or You can convert your json data to an Angular service (actually an Angular constant can work). Then my external file will be easy to grab in the tests, ex:

var setupData = $injector.get('SampleData');
$httpBackend.whenGET('/my-service-url').respond(SampleData);
$httpBackend.flush();

Upvotes: 0

Related Questions