Typescript 使用动态导入时jest与自定义错误类型不匹配

Typescript 使用动态导入时jest与自定义错误类型不匹配,typescript,jestjs,Typescript,Jestjs,我已定义此自定义错误(文件名:“errors.ts”): 导出类CustomError扩展错误{ 构造函数(消息?:字符串){ 超级(信息); setPrototypeOf(这个,Error.prototype); this.name=this.constructor.name; } } 我让这个模块使用这个错误(文件名:'main.ts'): 从“/errors”导入{CustomError}; let called=假; 导出默认值{ throwAfterFirst:():void=>{

我已定义此自定义错误(文件名:“errors.ts”):

导出类CustomError扩展错误{
构造函数(消息?:字符串){
超级(信息);
setPrototypeOf(这个,Error.prototype);
this.name=this.constructor.name;
}
}
我让这个模块使用这个错误(文件名:'main.ts'):

从“/errors”导入{CustomError};
let called=假;
导出默认值{
throwAfterFirst:():void=>{
如果(调用)抛出新的CustomError();
调用=真;
},
};
我想使用动态导入检查jest,以便调用
jest.restModule()
重置
调用的
变量。这是测试文件:

从“/errors”导入{CustomError};
let main:typeof import('./main')。默认值;
const load=async():Promise=>{
jest.reset模块();
main=(等待导入('./main'))。默认值;
};
描述('Main',()=>{
beforeach(异步()=>{
等待加载();
});
它('should on second time',()=>{
manager.throwAfterFirst();
expect(()=>manager.throwAfterFirst()).tothrower错误(CustomError);
});
它('仍应再次抛出',()=>{
manager.throwAfterFirst();
expect(()=>manager.throwAfterFirst()).tothrower错误(CustomError);
});
});
现在,这是工作的一半,因为在每次测试之前模块确实被重置,但问题是
tothrower
没有正确匹配,我在第二行的两次测试中都得到以下错误:

expect(received).toThrowError(expected)

Expected constructor: CustomError
Received constructor: CustomError
.
.
.
这种奇怪的错误不会出现在常规错误中(例如,将
CustomError
替换为
TypeError
)。
另外,
CustomError
可以在不动态导入的情况下成功匹配。 例如,以下测试工作正常:

从“/errors”导入{CustomError};
从“/main”导入main;
描述('Main',()=>{
它('should on second time',()=>{
manager.throwAfterFirst();
expect(()=>manager.throwAfterFirst()).tothrower错误(CustomError);
});
});
因为我使用的是动态导入
CustomError
无法正确识别(可能不是同一个原型?)。我在这里遗漏了什么,如何修复测试?

(我仍然希望检查特定错误,并且不使用与任何错误匹配的
toThrow
。顺便说一句,toThrow
适用于此场景)。

我发现的解决方法是:

let main:typeof import('./main')。默认值;
let Errors:typeof import('./Errors');
const load=async():Promise=>{
jest.reset模块();
main=(等待导入('./main'))。默认值;
Errors=等待导入('./Errors');
};
描述('Main',()=>{
beforeach(异步()=>{
等待加载();
});
它('should on second time',()=>{
manager.throwAfterFirst();
expect(()=>manager.throwAfterFirst()).tothroweror(Errors.CustomError);
});
它('仍应再次抛出',()=>{
manager.throwAfterFirst();
expect(()=>manager.throwAfterFirst()).tothroweror(Errors.CustomError);
});
});