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

126
Visualizações
Should I test this code? (immediate method call assignment to class member)
class MyClassComponent {
  hasAccess = this.hasAccessToSomething();

  constructor(private numberService: NumberService) {}

  private hasAccessToSomething(): boolean {
    return this.numberService.getNumber() > 5;
  }
}

Should I test wheter hasAccess equals to false or true dependently on the numberService.getNumber() value? This is an initial class state where I called a private method, a method that isn't supposed to be tested, and assigned its value to my public class member.

If the answer is yes - how to do that using jasmine/jest with TestBed?

let component: MyClassComponent;

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      MyClassComponent,
      NumberService
    ]
  });

  component = TestBed.inject(MyClassComponent);
});

I could mock NumberService.getNumber method but the problem is that after the mock is created, I can't reinitialize hasAccess assignment. I could call this.hasAccessToSomething in e.g. ngOnInit and then test hasAccess value calling again ngOnInit but I wouldn't like to complicate class for tests purpose. With such easy class I could get rid of TestBed and reinitialize component using new MyClassComponent but let's imagine that this class is much bigger with much more dependencies.

How would you do that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use jasmine.Spy for such purpose and turn hasAccess into a getter property:

export class MyClassComponent {
  public get hasAccess(): boolean {
    return this.hasAccessToSomething()
  }
  ...

Inside your tests:

describe('MyClassComponent', () => {
  beforeEach(async () => {
    TestBed.configureTestingModule({
    providers: [
      MyClassComponent,
      NumberService
    ]
  });
    ...
  })

  it('should have access if numberService.getNumber() returns more than 5', () => {
    spyOn(TestBed.inject(NumberService), 'getNumber').and.returnValue(6)
    expect(component.hasAccess).toBeTrue()
  })


  it('should not have access if numberService.getNumber() returns less than 5', () => {
    spyOn(TestBed.inject(NumberService), 'getNumber').and.returnValue(4)
    expect(component.hasAccess).toBeFalse()
  })

})

if you DO NOT want to turn hasAccess into a getter property then you should scope the creation of the component right before mocking/spying on the service by using nested describe blocks:

describe('MyComponent...', () => {

  beforeEach(() =>  /*build the module*/)

  describe('when NumberService.getNumber returns more than 5', () => {
    beforeEach(() => {
      spyOn(TestBed.inject(NumberService), 'getNumber').and.returnValue(6)
      component = ...
    })

    it('should have access', () => expect(component.hasAccess).toBeTrue())
  })
  // Symmetric for less than 5
about 4 years ago · Juan Pablo Isaza Relatório

0

I believe that's what you looking for

let component: MyClassComponent;

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [MyClassComponent, NumberService],
  });
});

describe("with default NumberService result", () => {
  beforeEach(() => {
    component = TestBed.inject(MyClassComponent);
  });

    it('should ....',()=>{...})
});

describe("with mocked NumberService result", () => {
  beforeEach(() => {
    TestBed.overrideProvider(NumberService, {
      useValue: { getNumber: () => 999 },
    });
    component = TestBed.inject(MyClassComponent);
  });

    it('should ....',()=>{...})
});
about 4 years ago · Juan Pablo Isaza Relatório
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