I'm testing my application using Jest, but it's getting an error like:
SyntaxError: Unexpected token }
The line witch's occurring error 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 witch's occurring error 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');
 
    
    Works with Typescript / ts-jest 26.5 :
import * as myJson from './mock/MyJson.json';
...
const result = doAnyting(myJson);
 
    
    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.
 
    
    You need to import json from 'filename.json'. Make sure that if you're using path alias you need to configure them on your jest.config.js file inside the ModuleNameMapper config. 
 
    
    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.