Recently, I have been working on creating a quick mock function for a unit test. To ensure that my assertions are tested accurately, I need to include an HTML element on the page with stringified JSON content. The system under test manipulates the stringified JSON data, converts it back into regular JSON format, and re-inserts it.
While setting up my mock insertion into the DOM, I noticed a peculiar behavior where the stringified JSON is being treated as actual JSON instead of just a simple string.
Here's a snippet of the code I was working on:
var mockJson = JSON.stringify({
name: "Foo",
data: {}
});
var mockScript = document.createElement("script");
mockScript.id = "myElement";
mockScript.textContent = mockJson;
document.body.appendChild(mockScript);
Surprisingly, the above code works perfectly fine. Upon execution, the #myElement
element is appended to the DOM containing the stringified mock object.
However, an error is also thrown:
VM136:1 Uncaught SyntaxError: Unexpected token ':'
This error seems to be triggered specifically on the last line of the script. It was puzzling at first because there was no :
in that particular line. Eventually, I realized that the stringified mockJson
is being interpreted as JSON, causing this anomaly.
To delve deeper, I replaced the complex mock object with a simple string in my testing:
var mockJson = "foo";
var mockScript = document.createElement("script");
mockScript.id = "myElement";
mockScript.textContent = mockJson;
document.body.appendChild(mockScript);
Even with this change, the script performed as expected by displaying the string "foo" inside the script element in the DOM. However, an error emerged stating:
VM179:1 Uncaught ReferenceError: foo is not defined
Evidently, it was attempting to interpret foo
as a variable despite its declaration as a string.
What could be causing this dual behavior? While successfully incorporating the string as intended, why is it still generating an error?
Fiddle example
var mockJson = JSON.stringify({
name: "Foo",
data: {}
});
var mockScript = document.createElement("script");
mockScript.id = "myElement";
mockScript.textContent = mockJson;
document.body.appendChild(mockScript);