Lai32290
Lai32290

Reputation: 8548

How to import 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?

Upvotes: 47

Views: 52463

Answers (8)

Andreas
Andreas

Reputation: 444

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');
    

Upvotes: 24

Coffee-Tea
Coffee-Tea

Reputation: 1188

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

Upvotes: 1

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

Upvotes: 0

Michael Rovinsky
Michael Rovinsky

Reputation: 7210

Works with Typescript / ts-jest 26.5 :

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

...

const result = doAnyting(myJson);

Upvotes: 21

exmaxx
exmaxx

Reputation: 3639

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.

Upvotes: 14

aoh
aoh

Reputation: 1160

const myJSON = require('./json_file_name.json')

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

Upvotes: 2

strix25
strix25

Reputation: 583

const someObject = require('./somefile.json')

Upvotes: 1

Diogo Mafra
Diogo Mafra

Reputation: 479

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.

Upvotes: 6

Related Questions