Pregunta

I'm running Karma 12.19 and using Jasmine to do unit tests. The only failing test fails at JSON.parse function.

Trace:

SyntaxError: Unexpected token d
    at Object.parse (native)
    at /var/html/components/src/controllers/MainCtrl.js:9:8129
    at /var/html/libs/angular/angular.min.js:72:199
    at J (/var/html/libs/angular/angular.min.js:99:469)
    at J (/var/html/libs/angular/angular.min.js:99:469)
    at /var/html/libs/angular/angular.min.js:101:126
    at k.$eval (/var/html/libs/angular/angular.min.js:111:353)
    at k.$digest (/var/html/libs/angular/angular.min.js:108:419)
    at k.$apply (/var/html/libs/angular/angular.min.js:112:173)
    at h (/var/html/libs/angular/angular.min.js:72:454)

Code fails at this line:

for (var i = 0; i < templates.length; i++) {
    templates[i].data = JSON.parse(templates[i].data); // here
}

The code runs as expected and without errors in production, but jasmine and/or Karma aren't handling it.

Test data:

var templates = [{data: "data", name: "name"}];

Any suggestions?

¿Fue útil?

Solución

You are trying to parse "data" to a JSON, which is not valid JSON. You can parse the whole templates to JSON but then you would have to wrap its declaration in sinqle quotes to make it a string:

var templates = '[{data: "data", name: "name"}]';

Or if you want to keep what you are doing put a valid JSON to the data property:

var templates = [{data: '{x: "something"}', name: "name"}];

Otros consejos

If you have a working javascript object (which is not necessarily a valid JSON object) that you would like to parse for testing, you can use something like:

var templates = [JSON.stringify({data: "data", name: "name"})];

This should work for you

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top