typescript - Angular testi taklit abone olunan özellik
İki özelliğe sahip bir servisime var:
Hizmet
...
public usernameAnnounced;
private username: Subject<string> = new Subject<string>();
constructor() {
super();
this.usernameAnnounced = this.username.asObservable();
}
Bileşenimde özelliğe abone olmak istiyorum:
Bileşen
public ngOnInit(): void {
this.service.usernameAnnounced.subscribe((username: string) => {
this.username = NavbarComponent.capitalizeFirstLetter(username);
});
}
Başka bir bilgisayarda kullanıcı adına yayın yapıyorum ama bu soru için önemsiz. Şimdi usernameAnnounced’i taklit etmek istiyorum ama bunu yapmakta zorluk çekiyorum. Bunu spyOn ile denedim ve bana şu hatayı veriyor: 'usernameAnnounced bir fonksiyon değil.' spyOnProperties ile denediğimde ise şu hatayı veriyor: 'özellik bir getter değil.'
Test edilmiş bilgisayar
şu ana kadar yaklaşımım şu şekilde görünüyor:
beforeEach(async(() => {
TestBed.configureTestingModule({
...
declarations: [NavbarComponent],
providers: [
...,
{provide: service, useValue: authenticationMock}
]
})
.compileComponents();
fixture = TestBed.createComponent(NavbarComponent);
}));
...
it('should render username',() => {
const underTest = fixture.componentInstance;
spyOnProperty(authenticationMock, 'usernameAnnounced').and.returnValue({
subscribe: () => {'boboUser'}}); <== important part here
underTest.ngOnInit();
fixture.detectChanges();
const compiled: HTMLElement = fixture.debugElement.nativeElement.querySelector('#userName');
const rendered: string = compiled.textContent;
expect(rendered).toMatch(`Logged in as: ${underTest.username}`);
});
Birinin herhangi bir ipucu var mı?
Cevap #1
Çözümü şu şekilde buldum: Öncelikle şöyle bir jasmine.spyObj oluşturmak:
const authenticationMock: AuthenticationService = jasmine.createSpyObj('AuthenticationService',
['usernameAnnounced']);
Bunu sahte servise atayın: {provide: AuthenticationService, useValue: authenticationMock}. Ve birim testinin kendisinde sadece özelliği beklenen sonucunla atayın:
const spy = TestBed.get(AuthenticationService);
spy.usernameAnnounced = Observable.of('dummyUser');
Cevap #2
Her zaman sahte nesnemde bir Subject (veya BehaviorSubject) oluşturmam gerekiyordu.
class authenticationMock{ // is the mock of AuthenticationService
public usernameAnnounced:Subject<string> = new Subject<string>();
}
...
// in Test
let authenticationService = TestBed.get(AuthenticationService)
...
authenticationService.next('myNewUser');
saygılarımla
