43

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
  • 22,209
  • 7
  • 57
  • 64
Lai32290
  • 8,062
  • 19
  • 65
  • 99
  • 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

8 Answers8

23

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
  • 416
  • 1
  • 4
  • 8
13

Works with Typescript / ts-jest 26.5 :

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

...

const result = doAnyting(myJson);
Michael Rovinsky
  • 6,807
  • 7
  • 15
  • 30
  • 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
10

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
  • 3,252
  • 28
  • 27
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
  • 449
  • 5
  • 9
2
const myJSON = require('./json_file_name.json')

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

aoh
  • 1,090
  • 2
  • 13
  • 25
1
const someObject = require('./somefile.json')
strix25
  • 543
  • 2
  • 10
  • 22
1

Set "esModuleInterop": true, in tsconfig.spec.json compilerOptions.

Coffee-Tea
  • 1,139
  • 9
  • 10
0

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