9

I am trying to mock the file-type library in a jest test. In my javascript file, I use this library in the following way:

import * as fileType from 'file-type';

....
const uploadedFileType = fileType(intArray);

Then, in my jest test, I am doing:

jest.mock('file-type');
import * as fileType from 'file-type';

and then trying to mock out the response in the following way:

fileType = jest.fn();
fileType.mockReturnValue({ ext: 'jpg' });

However, I get the error "fileType" is read-only.

Does anyone have an idea as to what I'm doing wrong? Thanks in advance.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user3802348
  • 2,502
  • 11
  • 36
  • 49

1 Answers1

6

If you only need the same return type in all test you can mock it like this

jest.mock('fileType', ()=> () => ({
  ext: 'jpg'
}))

This will mock the module so fileType() will always return {ext: 'jpg'}.

If you need different return values during your test you need to mock the module so it returns a spy where you can set the mock result later in the test using mockImplementation:

import fileType from 'fileType'
jest.mock('fileType', ()=> jest.fn())

fileType.mockImplementation(() => ({
  ext: 'jpg'
}))
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297