【发布时间】:2021-06-27 11:37:03
【问题描述】:
我正在尝试测试 SignalR HubConnection 的 onclose 回调,但我找不到如何触发 onclose 回调。
这是我要测试的:
@Injectable({
providedIn: 'root'
})
export class CloseConnectionHandlerService {
constructor(
private signalRService: SignalRService) {
}
public initialize(): void {
this.signalRService.hubConnection?.onclose((error: any) => {
if (error) {
console.error(error);
}
});
}
}
我正在尝试使用以下代码:
describe('CloseConnectionHandlerService', () => {
let service: CloseConnectionHandlerService;
let signalRServiceSpy: jasmine.SpyObj<SignalRService>;
beforeEach(() => {
signalRServiceSpy = {
...jasmine.createSpyObj('SignalRService', ['']),
} as jasmine.SpyObj<SignalRService>;
TestBed.configureTestingModule({
providers: [
{provide: SignalRService, useValue: signalRServiceSpy},
]
});
service = TestBed.inject(CloseConnectionHandlerService);
});
describe('#initialize', () => {
it('should log error to the console', () => {
// Arrange
spyOn(console, 'error');
const hubConnectionStartSpy = jasmine.createSpyObj(HubConnection, ['onclose']);
hubConnectionStartSpy.onclose.and.callFake(() => 'Error!');
signalRServiceSpy.hubConnection = hubConnectionStartSpy
// Act
service.initialize();
// Assert
expect(console.error).toHaveBeenCalled();
});
});
});
当我运行它时,我得到了 console.error 没有被调用的错误。有人知道我该如何测试吗?
【问题讨论】:
标签: javascript angular unit-testing callback jasmine