Javascript 向Jest命名空间添加新的自定义api方法定义

Javascript 向Jest命名空间添加新的自定义api方法定义,javascript,angular,jestjs,angular10,Javascript,Angular,Jestjs,Angular10,我之前使用Jasmine作为angular的测试平台,最近我转向jest框架,因为它作为测试平台提供了更多好处 当我将所有现有的UT迁移到Jest时,我发现Jest不支持某些API, 例如:createSpyObj(…) 为此,我必须使用jest.fn()创建一个helper方法,如下所示 const createSpyObj = (object: string, methods?: string[], properties?: any) => { const obj: any =

我之前使用Jasmine作为angular的测试平台,最近我转向jest框架,因为它作为测试平台提供了更多好处

当我将所有现有的UT迁移到Jest时,我发现Jest不支持某些API, 例如:
createSpyObj(…)

为此,我必须使用
jest.fn()
创建一个helper方法,如下所示

const createSpyObj = (object: string, methods?: string[], properties?: any) => {
   const obj: any = {};

   for (const method of methods) {
     obj[method] = jest.fn();
   }

   for (const key of Object.keys(properties)) {
     obj[key] = jest.fn().mockReturnValue(properties[key]);
   }

   return obj;
 };
这很好,但是,我想将其添加到Jest名称空间中,这样就不必在每个测试文件中定义它

到目前为止,我就是这么做的(在这篇文章之后,):

  • 用下面的代码创建了一个文件
    jest.d.ts
    ,并在
    “include”中添加了此文件路径“:[…,”/jest.d.ts“],
    tsconfig.json

    declare namespace jest {
       function createSpyObj<T>(object: string, methods?: string[], properties?: any): T;
    }
    
  • 有什么问题吗?
    jest.setup.ts
    中获取错误,因为“类型'typeof jest'上不存在属性'createSpyObj'

    但是当我在测试中使用新的API
    jest.createdSpyObj(…)
    时,我没有得到任何编译时错误,这意味着新的方法声明工作正常,但在运行时失败


    非常感谢任何快速帮助

    扩展不属于您的API以满足您自己的需要是一种不好的做法。如果您需要在测试中使用createSpyObj,您可以将其设置为全局的,这样就可以
    声明var createSpyObj
    。尝试
    typeroot
    来指定自定义类型,而不是
    include
    @EstusFlask,这是您的权利,但我并没有改变lib的现有定义,只是对其进行了修补。这样我就可以将它用作
    jest.createSpyObj
    ,它的语法或多或少与jasmine lib的语法相同。@EstusFlask顺便问一下,您有没有使用
    typeRoots
    的示例可以试用?
     jest.createSpyObj = (object: string, methods?: string[], properties?: any) => {
       const obj: any = {};
    
       for (const method of methods) {
         obj[method] = jest.fn();
       } 
    
       for (const key of Object.keys(properties)) {
         obj[key] = jest.fn().mockReturnValue(properties[key]);
       }
    
       return obj;
     };