Reputation: 8548
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
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
Reputation: 1188
Set "esModuleInterop": true,
in tsconfig.spec.json
compilerOptions.
Upvotes: 1
Reputation: 21
You need to remove ',' before all the '}'. I found this solution by test and error.
Upvotes: 0
Reputation: 7210
Works with Typescript / ts-jest 26.5
:
import * as myJson from './mock/MyJson.json';
...
const result = doAnyting(myJson);
Upvotes: 21
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
Reputation: 1160
const myJSON = require('./json_file_name.json')
Note that myJSON
is already an object, no need to use JSON.parse
Upvotes: 2
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