Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
Property assignment in parent class works in fiddle, does not work in test

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?

about 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda