#angular #unit-testing #websocket #karma-jasmine #behaviorsubject
Вопрос:
Получение ошибки при модульном тестировании websocket
Error: <spyOn> : webSocket is not declared writable or has no setter
Usage: spyOn(<object>, <methodName>)
вот мой сервис и компонент
// tikcet.service.ts
import { webSocket } from 'rxjs/webSocket';
export class ticketService {
ticketVar: number = 0;
private ticketCtrl = new BehaviorSubject(this.ticketVar);
setTicketSubject(value: number) {
this.ticketCtrl.next(value)
}
getTicketSubject() {
return this.ticketCtrl.asObservable();
}
getRealtimeTicket() {
return webSocket('ws://localhost:8081');
}
и в моем ticket-component.ts
// ticket-component.ts
constructor(private ticketService: TicketService) {
this.ticketSubscription = this.ticketService.getRealtimeTicket().subscribe(
data => {
this.ticketService.setTicketSubject(data);
}
)
}
ngOnInit(): void {
this.realtimeTicketSubscription = this.ticketService.getTicketSubject().subscribe(
ticket => {
this.ticketLoader = ticket;
}
)
}
// ticket.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { BehaviorSubject } from 'rxjs';
import * as rxJsWebSocket from 'rxjs/webSocket';
import { TicketService } from './ticket.service';
describe('TicketService', () => {
let ticketService: TicketService,
httpClientTestingModule: HttpClientTestingModule;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule
],
providers: [
TicketService
]
});
ticketService = TestBed.inject(TicketService);
httpClientTestingModule = TestBed.inject(HttpClientTestingModule);
});
it('should return correct beh subject', () => {
const testTicket: number = 433;
ticketService.setTicketSubject(testTicket);
ticketService.getTicketSubject()
.subscribe(response => {
expect(response).toBe(433);
});
});
it('should return latest realtime ticket', () => {
const testTicket: number = 433;
let subject = new BehaviorSubject(testTicket);
const webSocketSpy = spyOn(rxJsWebSocket, 'webSocket').and.returnValue(<any>subject);
expect(ticketService.getRealtimeTicket()).toBe(<any>subject);
expect(webSocketSpy).toHaveBeenCalledWith('ws://localhost:8081');
});
})