fix(testing): correctly throw in constructor with spy() (#5139)

This commit is contained in:
Yoshiya Hinosawa 2024-06-26 16:32:08 +09:00 committed by GitHub
parent 040e666033
commit 06d43901a8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 1 deletions

View File

@ -759,10 +759,11 @@ function constructorSpy<
const calls: SpyCall<Self, Args, Self>[] = [];
// @ts-ignore TS2509: Can't know the type of `original` statically.
const spy = class extends original {
// deno-lint-ignore constructor-super
constructor(...args: Args) {
super(...args);
const call: SpyCall<Self, Args, Self> = { args };
try {
super(...args);
call.returned = this as unknown as Self;
} catch (error) {
call.error = error as Error;

View File

@ -510,6 +510,21 @@ Deno.test("spy() works on constructor of child class", () => {
assertSpyCalls(PointSpy, 1);
});
Deno.test("spy() works on constructor that throws an error", () => {
class Foo {
constructor() {
throw new Error("foo");
}
}
const FooSpy = spy(Foo);
assertThrows(() => new FooSpy(), Error, "foo");
assertSpyCall(FooSpy, 0, {
self: undefined,
args: [],
error: { Class: Error, msgIncludes: "foo" },
});
});
Deno.test("spy() works with throwing method", () => {
const obj = {
fn() {