Currently, I am working on an AngularJS project that utilizes Karma to execute some unit tests directly in the browser. To conduct these tests, I have opted for mocha as the test framework.
The challenge I am facing lies in running specification tests that require access to JSON files to verify if they conform to specific conventions such as types and naming conventions.
I want to emphasize that I am interested in testing the actual content of these files, not a modified version through Angular Mock's $httpBackend
.
To make the JSON files accessible, I have configured them to be served in my karma.conf.js
file.
files: [
{ pattern: 'static/assets/json/cards/*.json', included: false, served: true },
'path/to/angular.js',
'path/to/angular-mocks.js',
'tests/**/*.js'
]
After initiating the command karma start
, I can visit
/base/static/assets/json/cards/something.json
and confirm that the files are being served correctly.
Subsequently, in my test suite, I inject both the $http
and $q
services.
var $http, $q;
beforeEach(module('chai'));
beforeEach(inject(function(_$http_, _$q_) {
$http = _$http_;
$q = _$q_;
}));
My approach involves loading each resource using $http.get
, gathering the promises returned from $http.get
, then utilizing $q.all
to ensure all promises are fulfilled before proceeding with the tests.
it('should load the resources', function(done) {
var promises = ['admissions.json', 'discharge.json']
.map(function(resource) {
console.log('Loading', resource);
return $http.get('/base/static/assets/json/cards/' + resource);
});
$q.all(promises)
.then(function(card) {
console.log('Success');
done();
}, function(err) {
console.log('Failure', err);
done();
});
});
However, when I run my tests, I encounter the following error in the console:
Loading admissions.json
Loading discharge.json
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
Initially, I suspected that the time taken to load the files might be causing the timeout issue, but the size of the file is only 95kb.
Then I considered whether the custom promise interface (.success
and .error
) was disrupting the functioning of $q.all
. However, this does not seem to be the case.
Finally, I attempted to send a standalone request for
/base/static/assets/json/cards/admissions.json
at the beginning of the tests. Despite receiving a promise as expected, it never resolves since there is no response sent back. Upon inspecting the network tools, I discovered that the request isn't even initiated. The code does run, but for some reason, $http
fails to make the request.
My current assumption is that this could be related to Angular Mocks intercepting $http
requests for its own $httpBackend
service. How can I work around this obstacle?