I'm testing my application using Jest, but it's getting an error like:
SyntaxError: Unexpected token }
The line where the error is occurring is:
import { something } from "../my-json.json";
How can I import the JSON file on Jest tests?
I'm testing my application using Jest, but it's getting an error like:
SyntaxError: Unexpected token }
The line where the error is occurring is:
import { something } from "../my-json.json";
How can I import the JSON file on Jest tests?
As decribed here: is there a require for json in node.js you can use:
import someObject from ('./somefile.json')
This should also work:
const testObject = require('../config/object');
However, while I was using jest for testing I got it working by saving the json with .js extension and inside it using module.exports. Then I destructured the object in my main file.
JSON file (object.js):
module.exports = {
"testObject":
{
"name": testName
"surname": testSurname
}
}
Main File
const { testObject } = require('./config/object');
XML files... SyntaxError: Unexpected token '<'Works with Typescript / ts-jest 26.5 :
import * as myJson from './mock/MyJson.json';
...
const result = doAnyting(myJson);
import myJson from './mock/MyJson.json'; returned undefined for me. Changing to import * as myJson from './mock/MyJson.json'; did the trick with Typescript and ts-nodeimport * as myJson from './MyJson.json' saved me.When using Typescript and Vue CLI, all I needed to do was to add resolveJsonModule to tsconfig.ts:
// tsconfig.ts
{
"compilerOptions": {
"resolveJsonModule": true,
}
}
This in fact solves the loading of JSON files by Typescript in general.
Note: I am using Vue CLI so it is possible that some JSON related config is already preconfigured there.
const myJSON = require('./json_file_name.json')
Note that myJSON is already an object, no need to use JSON.parse
You need to remove ',' before all the '}'. I found this solution by test and error.