This question is similar to Can you limit the scope of a TypeScript global type? but a little different (though I would love an answer to it, as well).
In Jest, I want to do something like:
declare global {
namespace jest {
interface Matchers<R> {
toBeAwesome(this: Matchers<void, HTMLElement>): R;
}
}
}
export {};
expect.extend({
toBeAwesome() {
// ...
}
});
However, I only call extend in that specific file, and therefore I do not want other test files to be able to access it. The declare global {} bit seems to screw me over.
I've also tried something hacky:
declare const expect: jest.Expect & {
<T = any>(actual: T): jest.JestMatchers<T> & {
toBeSelected(this: jest.Matchers<void, HTMLElement>): void;
};
};
But the method won't even show up.
I also tried directly declaring namespace jest outside of the global scope, but since jest is a global namespace, it created a new namespace instead of augmenting the other.
Is it possible to scope an augmentation to a specific file and any file that imports it?
I don't think you can limit the scope of an augmented type within the same package, but you could define your own expect function with the type you want:
Something like:
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
}
Then, arguably your tests are more explicit:
it("should be awesome", () => {
expectElement(el).toBeAwesome()
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With