gpt4 book ai didi

typescript - 将 jest 的 expect.extend() 与 TypeScript 的范围限定为单个测试文件

转载 作者:行者123 更新时间:2023-12-05 05:59:56 24 4
gpt4 key购买 nike

这个问题类似于Can you limit the scope of a TypeScript global type?但有点不同(尽管我也很想回答这个问题)。

在 Jest 中,我想做类似的事情:

declare global {
namespace jest {
interface Matchers<R> {
toBeAwesome(this: Matchers<void, HTMLElement>): R;
}
}
}

export {};

expect.extend({
toBeAwesome() {
// ...
}
});

但是,我只在该特定文件中调用了 extend,因此我不希望其他测试文件能够访问它。 declare global{} 位似乎把我搞砸了。

我也尝试过一些 hacky:

declare const expect: jest.Expect & {
<T = any>(actual: T): jest.JestMatchers<T> & {
toBeSelected(this: jest.Matchers<void, HTMLElement>): void;
};
};

但是这个方法甚至不会出现。

我也尝试在全局范围之外直接声明 namespace jest,但是由于 jest 是一个全局命名空间,它创建了一个新的命名空间而不是扩充另一个命名空间。

是否可以将扩充范围限定到特定文件和导入它的任何文件?

最佳答案

我不认为你可以在同一个包中限制扩充类型的范围,但你可以用你想要的类型定义你自己的 expect 函数:

类似于:

function expectElement(actual: HTMLEelement): ElementExpect {
return expect(actual) as any as ElementExpect
}

type ElementExpect = JestExpect & ElementMatchers

interface ElementMatchers<R = void> extends Matchers<void> {
toBeSelected(): R
}

然后,可以说您的测试更明确:

it("should be awesome", () => {
expectElement(el).toBeAwesome()
})

关于typescript - 将 jest 的 expect.extend() 与 TypeScript 的范围限定为单个测试文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67894491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com