Skip to content

Instantly share code, notes, and snippets.

@dubzzz
Last active April 2, 2019 21:29
Show Gist options
  • Save dubzzz/edd7aafc209fa8c2acfe2f6fe6f4be72 to your computer and use it in GitHub Desktop.
Save dubzzz/edd7aafc209fa8c2acfe2f6fe6f4be72 to your computer and use it in GitHub Desktop.
jest-typings-for-tobeinstanceof
class A {
a() { }
}
class B {
b() { }
}
class C extends B {
c() { }
}
class HasStaticNameMethod {
constructor() {}
static plop() {}
}
function DefinesNameProp(): void {}
Object.defineProperty(DefinesNameProp, 'plop', {
configurable: true,
enumerable: false,
value: '',
writable: true,
});
function LegacyClass(): void {
this.a = 9;
}
declare function foo<T>(): T;
// expect(...).toBeInstanceOf
type Matcher<T> = {
toBeInstanceOf<U extends Partial<T>>(expected: U | { new(...args: any[]): U }): T;
};
declare function expect<T = unknown>(t: T): Matcher<T>;
/****************************************/
/* Cases extracted from Jest Unit-Tests */
/****************************************/
// jestExpect(a).toBeInstanceOf(b)
expect(new Map()).toBeInstanceOf(Map);
expect([]).toBeInstanceOf(Array);
expect(new A()).toBeInstanceOf(A);
expect(new C()).toBeInstanceOf(B);
expect(new HasStaticNameMethod()).toBeInstanceOf(HasStaticNameMethod);
// jestExpect(a).not.toBeInstanceOf(b);
expect('a').toBeInstanceOf(String); // TypeScript warns for incorrect types
expect(1).toBeInstanceOf(Number); // TypeScript warns for incorrect types
expect(true).toBeInstanceOf(Boolean); // TypeScript warns for incorrect types
expect(new A()).toBeInstanceOf(B); // TypeScript warns for incorrect types
expect(Object.create(null)).toBeInstanceOf(A);
expect(undefined).toBeInstanceOf(String); // TypeScript warns for incorrect types
expect(null).toBeInstanceOf(String); // TypeScript warns for incorrect types
expect(/\w+/).toBeInstanceOf(function() {}); // TypeScript warns for incorrect types
expect(new DefinesNameProp()).toBeInstanceOf(RegExp);
/****************************************/
/* Custom cases */
/****************************************/
// NO TypeScript errors
expect(new DefinesNameProp()).toBeInstanceOf(DefinesNameProp);
expect(new A()).toBeInstanceOf(A);
expect(new C()).toBeInstanceOf(B);
expect(new LegacyClass()).toBeInstanceOf(LegacyClass);
expect(foo<B>()).toBeInstanceOf(C);
expect(foo<C>()).toBeInstanceOf(B);
expect({}).toBeInstanceOf(LegacyClass); // arf...
expect(new DefinesNameProp()).toBeInstanceOf(HasStaticNameMethod); // arf...
// WITH TypeScript errors
expect(foo<C>()).toBeInstanceOf(A);
expect(foo<A>()).toBeInstanceOf(C);
@dubzzz
Copy link
Author

dubzzz commented Apr 2, 2019

With all options enabled:

  • noImplicitAny
  • strictNullChecks
  • strictFunctionTypes
  • strictPropertyInitialization
  • noImplicitThis
  • noImplicitReturns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment