I have the following ts fiddle:
class BaseFoo {
name: string;
constructor(
name: string,
) {
console.log("In Parent Constructor");
this.name = name;
console.log("this.name in parent constructor " + this.name);
}
getFooBar(): string {
throw "Not implemented";
}
}
class Foo extends BaseFoo {
name!: string;
constructor(name: string) {
super(name);
console.log("this.name in child constructor " + this.name);
// this.elementValue = elementValue;
}
getFooBar(): string {
return this.name;
}
}
class CardObject {
name: Foo;
constructor(my_name: string) {
this.name = new Foo(my_name);
}
}
let c = new CardObject("baz")
console.log(c.name.getFooBar())
In the fiddle, the following output is logged:
[LOG]: "this.name in parent constructor baz"
[LOG]: "this.name in child constructor baz"
[LOG]: "baz"
Which is exactly what I would expect.
In my actual project (a react project) I am running tests using react-scripts test. My code looks like this:
// foo.tsx
class BaseFoo {
name: string;
constructor(name: string) {
console.log("In Parent Constructor");
this.name = name;
console.log("this.name in parent constructor " + this.name);
}
getFooBar(): string {
throw "Not implemented";
}
}
export class Foo extends BaseFoo {
name!: string;
constructor(name: string) {
super(name);
console.log("this.name in child constructor " + this.name);
}
getFooBar(): string {
return this.name;
}
}
And my test looks like this:
import {Foo} from "../foo"
describe("Foo", () => {
it("has a weird bug", () => {
let my_foo = new Foo("Baz");
console.log(my_foo.getFooBar());
});
});
When I run the test with npm react-scripts test, the following output is logged:
this.name in parent constructor Baz
this.name in child constructor undefined
undefined
Very confused here to why the child object seems to not get the property assigned to it. What's going on here? Is this a quirk with react-scripts test? Something to do with how the module is exported?