Javascript 向Jest命名空间添加新的自定义api方法定义
我之前使用Jasmine作为angular的测试平台,最近我转向jest框架,因为它作为测试平台提供了更多好处 当我将所有现有的UT迁移到Jest时,我发现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 =
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'
但是当我在测试中使用新的APIjest.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;
};