Alex
Alex

Reputation: 2780

Import a mock JSON file for Jest/Axios upload test

I am looking to test Axios functionality of a method which posts a file using Jest.

As part of this I would like to POST a local mocked JSON file, is that possible?

I can't see any way to require or import a JSON file for uploading in a POST.

// import jsonFileMock from "../__mocks__/jsonFileMock.json"; 
import jsonFileMock = require("../__mocks__/jsonFileMock.json"); 

const apiResponse = await someApiUpload(jsonFileMock); // Doesn't work

Upvotes: 0

Views: 559

Answers (1)

Seth Lutske
Seth Lutske

Reputation: 10686

You're mixing ES6 import with commonjs require. Try

import * as jsonFileMock from "../__mocks__/jsonFileMock.json"

A json file can't have an export statement, so thats why you have to use the * as term. You can also just fetch it:

fetch('../__mocks__/jsonFileMock.json')
  .then( async data => await someApiUpload(data) )

More about importing a json file can be found in the question How to import a json file in ecmascript 6?

Upvotes: 1

Related Questions