设置笑话模拟 - 一种方法有效,另一种方法无效

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

当为 class 设置玩笑模拟时,对我不起作用并出现错误“_TextObj.TextObj 不是构造函数”的是

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

      }
   });
});

根据 https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter 我曾预计第一个版本也能工作 - 还是不行?

然而有效的是

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

TextObj 是命名导出,您正在尝试模拟默认导出,这就是它抛出错误 _TextObj.TextObj is not a constructor.

的原因

对于模拟命名导出,您需要进行以下更改,即 return 包含 TestObj 属性:

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

      }
   });
});