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?
CodePudding user response:
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
