0

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
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Alex
  • 2,651
  • 2
  • 25
  • 45

1 Answers1

1

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?

Seth Lutske
  • 9,154
  • 5
  • 29
  • 78
  • Thanks I did read that thread but it was more to do with reading the contents of the file rather than uploading it, I will give fetch a go now. – Alex Jul 30 '20 at 15:21
  • Jest doesn't like fetch apparently, I'm not convinced using wildcard * with import will work to be honest. – Alex Jul 30 '20 at 15:23
  • I understand, but you can't upload data coming from your `import jsonFileMock = require("../__mocks__/jsonFileMock.json");` statement, as that statement doesn't make sense to javascript – Seth Lutske Jul 30 '20 at 15:25
  • Yup, that's about where I got to with it as well :) – Alex Jul 30 '20 at 15:28