简体   繁体   中英

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM