Skip to content

Instantly share code, notes, and snippets.

@occar421
Created July 9, 2022 14:21
Show Gist options
  • Save occar421/fa899db12e73dc0135d860de90275a0b to your computer and use it in GitHub Desktop.
Save occar421/fa899db12e73dc0135d860de90275a0b to your computer and use it in GitHub Desktop.
AsymmetricMatcher to Imperative assertions.
/// <reference types="jest" />
declare namespace jest {
interface Expect {
that(fn: (target: any) => void): any;
}
interface InverseAsymmetricMatchers {
that(fn: (target: any) => void): any;
}
}
// @ts-expect-error
global.expect.that = (fn: any) => new That(fn);
// @ts-expect-error
global.expect.not.that = (fn: any) => new That(fn, true);
class That extends AsymmetricMatcher<(target: any) => void> {
asymmetricMatch(other: unknown): boolean {
if (this.inverse) {
try {
this.sample(other);
return false; // should be fail
} catch (e: any) {
return true;
}
}
this.sample(other);
return true;
}
toString() {
return `${this.inverse ? "Not" : ""}That`;
}
override toAsymmetricMatcher() {
return `That`;
}
}
test("", () => {
const target = { a: new Error("aaa"), };
expect(target).toEqual(expect.objectContaining({
a: expect.that((a) => {
expect(a).toBeInstanceOf(Error);
}),
})).
expect(target).toEqual(expect.objectContaining({
a: expect.not.that((a) => {
expect(a).toBeInstanceOf(URL);
}),
})).
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment