2

I have mock data in an external json file that I want to have available for Jasmine unit tests in Angular.js. Unfortunately I am not approved to run node.js in my dev environment, so the usual karma examples don't apply to me.

I have tried:

beforeEach(inject(function ($injector, $http) {
    console.log('this gets called');
    $http.get('/mockData/surveySetup.json').success(function (data) {
            console.log('this never gets called');
        }).error(function () {
            console.log('this never gets called');
        });
}));

The console.log outside of the $http.get gets called, but the ones inside $http.get never fire, and I don't see a call to the json file in chrome's network tab.

What can I do to load this file to use in my tests? At the end of the day I just need to have access to the data in the .json file so I can refer to it in my unit tests.

Thanks in advance.

2 Answers 2

2

I found that I needed to convert my .json file to an Angular service (actually an Angular constant worked for my purposes). Then my external file was easy to grab in my tests, like so:

var setupData = $injector.get('SetupData');
$httpBackend.whenGET('/surveySetup').respond(setupData);
$httpBackend.flush();
Sign up to request clarification or add additional context in comments.

3 Comments

I cannot understand what you mean by "convert my .json file to an Angular service"
can you please give detail of what you did
@imbalind, Rishabh Jain, you need to take your static .json file and turn it in to a regular javascript object. Then make it available to your app as an Angular constant.
0

Not sure what exactly are going to achieve but usually you can configure this by using $httpBackend which can be configured to mock the actual requests from any of your code (you may also need to setup with your URL syntax in this case but anyway this the common case for the unit tests. In this case you don't need to read the JSON file you can just provide the JS object inside of the $httpBackend configuration for that URL and when this URL is to be invoked $httpBackend will return the specified object. Look at: $httpBackend

1 Comment

Thanks, but I already have the file which I use elsewhere. I'm trying to avoid repeating code. I really need to be able to load the data from the file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.