gpt4 book ai didi

angular - 如何在 Angular 单元测试中建立 websocket 连接?

转载 作者:太空狗 更新时间:2023-10-29 18:36:54 25 4
gpt4 key购买 nike

我正在开发一个 Angular (v 6.1.0) 应用程序,它通过 websocket 与后端通信。到目前为止,除了单元测试外,一切都运行良好。为了测试我的组件,我创建了一个模拟后端,但我无法在模拟后端和测试模块之间建立连接。我使用 Jasmine 作为断言库,使用 Jest 作为测试运行器,这是一个示例测试套件:

describe('RandomComponent', () => {
let component: RandomComponent;
let fixture: ComponentFixture<RandomComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [SomeModule],
providers: [SpecialWebSocketService, WebSocketService,
{ provide: BackendUrlService, useClass: BackendUrlMockService }
]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(RandomComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create random component', () => {
expect(component).toBeTruthy();
});
});

BackendUrlMockService 只是为了提供一个 URL。单个测试用例产生以下内容:

 FAIL  src/app/path/to/my/random.component.spec.ts
RandomComponent
✕ should create random component (603ms)

● RandomComponent › should create random component

InvalidStateError: Still in CONNECTING state.

应用程序在真实后端和模拟后端上都能正常工作。测试模块两者都不适用。我还注意到,如果我向测试用例添加超时:

it('should create random component', (done) => {
setTimeout(() => {
expect(component).toBeTruthy();
done();
}, 1000);
});

我的模拟后端记录了一条消息,表明连接已正确建立,但我仍然收到错误消息。有谁知道如何正确设置所有内容以便我可以测试我的组件?

最佳答案

基于@user184994 的评论,我决定模拟 websocket 而不是后端:

const mockData = {
// some arbitrary data
};

class WebSocketServiceSpy {

private messageSpy = new Subject<string>();
private messageHandler = this.messageSpy.asObservable();

createObservableSocket(url: string): Observable<string> {
console.log(`Websocket would connect to ${url}.`);

return new Observable(observer => {
this.messageHandler.subscribe(() => {
observer.next(JSON.stringify(mockData));
});
});
}

sendMessage(message: any) {
this.messageSpy.next();
}
}

然后,我在测试模块中使用它:

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [],
imports: [SomeModule],
providers: [SpecialWebSocketService, BackendUrlService,
{ provide: WebSocketService, useClass: WebSocketServiceSpy }
]
})
.compileComponents();
}));

测试终于通过了:

PASS  src/app/path/to/my/random.component.spec.ts
● Console

console.log src/app/path/to/my/random.component.spec.ts:911
Websocket would connect to <actual url>.

关于angular - 如何在 Angular 单元测试中建立 websocket 连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52037268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com