Source:  Twitter logo

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:

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.

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'
5 users liked answer #0dislike answer #05
Andreas Köberle profile pic
Andreas Köberle

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).