stands2reason
stands2reason

Reputation: 730

Angular karma-jasmine: Included file cannot be found by XHR/GET

I have included an existing project file in my karma.conf.js files array:

files : [
  'app/bower_components/angular/angular.js',
  'app/bower_components/angular-route/angular-route.js',
  'app/bower_components/angular-mocks/angular-mocks.js',
  'app/js/**/*.js',
  'test/unit/**/*.js',
  'bower.json',
  'app/data/file.json',
],

I know the file has been matched because I do not get a warning that WARN [watcher]: Pattern <pattern> does not match any file. I changed that line to a known non-existent file and back to double check.

My base path is the project root:

basePath : '../',

When Angular's controllersSpec.js runs, I use an XHR GET to synchronously load the file, but I get a HTTP 404. Where is the file?

//Synchronously GET the test data
var req = new XMLHttpRequest();
req.open('GET', 'app/data/file.json', false);
req.send(null);

var testData = JSON.parse(req.responseText);

Then, in the test shell, I see:

WARN [web-server]: 404: /app/data/file.json
<user agent> ERROR
  SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
  at <path to project>/test/unit/controllersSpec.js:12

Upvotes: 0

Views: 306

Answers (1)

brandonscript
brandonscript

Reputation: 72855

It looks to me like you're trying to load a local file with a GET request; depending on what port or host your server is running on, it may not be able to load it up via a relative path. Try instead pointing it to the full URL path including protocol and domain name, e.g.:

//Synchronously GET the test data
var req = new XMLHttpRequest();
req.open('GET', 'http://servername.com/app/data/file.json', false);
req.send(null);

var testData = JSON.parse(req.responseText);

Upvotes: 1

Related Questions