32

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?

skyboyer
  • 19,620
  • 7
  • 50
  • 62
Lai32290
  • 7,390
  • 18
  • 61
  • 89
  • If you using that json as mock you could also store it as object in js file and export it. Just easy solution :P – Harion Jan 24 '20 at 15:36
  • Does this answer your question? [is there a require for json in node.js](https://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js) – Michael Freidgeim Apr 18 '20 at 02:56

7 Answers7

19

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');
    
Andreas
  • 349
  • 1
  • 3
  • 7
  • Doesn't seem to work with `XML` files... `SyntaxError: Unexpected token ' – doublejosh Feb 17 '21 at 19:03
  • I can see that the original question addresses jest with javascript. So I cannot see where XML files get mixed up in this. Could you please elaborate...? – Andreas Mar 04 '21 at 17:43
7

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.

exmaxx
  • 2,744
  • 27
  • 25
5

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.

Diogo Mafra
  • 361
  • 3
  • 9
3

Works with Typescript / ts-jest 26.5 :

import * as myJson from './mock/MyJson.json';

...

const result = doAnyting(myJson);
Michael Rovinsky
  • 5,807
  • 7
  • 12
  • 28
  • 3
    japp, `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-node – Samuli Ulmanen Jan 19 '22 at 11:56
0
const someObject = require('./somefile.json')
strix25
  • 481
  • 1
  • 12
  • 21
0
const myJSON = require('./json_file_name.json')

Note that myJSON is already an object, no need to use JSON.parse

aoh
  • 920
  • 1
  • 9
  • 22
-2

You need to remove ',' before all the '}'. I found this solution by test and error.