TomFree
TomFree

Reputation: 1409

Setting up jest mocks - one way works the other doesn't

When setting up jest mocks for a class what does not work for me with an error of "_TextObj.TextObj is not a constructor" is

import { TextObj, } from "@entities/TextObj";
jest.mock('@entities/TextObj', () => {
   return jest.fn().mockImplementation((config: TextObjConfig) => {
      return { ...

      }
   });
});

According to https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter I had expected the first version to work too - or not?

however what works is

import { TextObj, } from "@entities/TextObj";
jest.mock('@entities/TextObj');
 ...
beforeAll(() => {
      TextObj.mockImplementation((config: TextObjConfig) => {
         return {
..
         }
      });
   });

Upvotes: 2

Views: 44

Answers (1)

Subrato Pattanaik
Subrato Pattanaik

Reputation: 6059

TextObj is a named export and you're trying to mock default export which is why it is throwing the error _TextObj.TextObj is not a constructor.

For mocking named export, you need to do following the changes i.e return an object that contains TestObj property:

import { TextObj, } from "@entities/TextObj";
jest.mock('@entities/TextObj', () => {
   TestObj: jest.fn().mockImplementation((config: TextObjConfig) => {
      return { ...

      }
   });
});

Upvotes: 1

Related Questions