gpt4 book ai didi

angular - 使用 socket.io 模型对 Angular 5 进行单元测试

转载 作者:行者123 更新时间:2023-12-02 20:21:49 25 4
gpt4 key购买 nike

我正在尝试对具有 socket.io 的服务进行单元测试使用 mock-socket 导入。我查看了类似的问题,例如 this一个,我无法让它与以下一起工作。

import { TestBed, inject, async } from '@angular/core/testing';
import { SocketIO, Server } from 'mock-socket';
import { BackendService } from './backend.service';

describe('BackendService', () => {

/* setup for mock-socket in order to test socket.io */
const SERVER_URL = window.location.host;
const mockServer = new Server(SERVER_URL);

// setting up server mock
mockServer.on('connection', socket => {
mockServer.emit('server-message', 'test message 1');
});

beforeEach(() => {

TestBed.configureTestingModule({
imports: [ ],
providers: [ BackendService ]
});

jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;

});

it('tests simple connection and messaging works with mock-socket setup', async(inject([BackendService], (service: BackendService) => {

(window as any).io = SocketIO;

// setting up client
service.socket = io(window.location.host);

setTimeout(() => {
service.socket.on('connect', (message) => {
expect(message).toEqual('test message 1');
mockServer.stop();
});
}, 100);

})));

});

有人遇到过这个问题吗?

我创建了一个 Stackblitz重新创建场景(如果它能让事情更容易理解)。

最佳答案

我通过更改为以下几行解决了我的问题:

  it('tests simple connection and messaging with mock-socket setup', async(done: DoneFn) => {

(window as any).io = SocketIO;

// setting up client
backendService.socket = io(window.location.host);


backendService.socket.on('server-message', (message) => {
console.log(message)
expect(message.message).toEqual('test message 1');
mockServer.stop();
done();
});

});

});

问题本身是由于您需要在asynchronous时通知Jasmine操作完成。

这是一个工作stackblitz查看测试是否有效。

关于angular - 使用 socket.io 模型对 Angular 5 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51205639/

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