Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda