如何解决如何使用Jestsocket.io从React测试中测试socket.on
我已经成功设置了可以正常运行的socket.io服务器,并使用Mocha成功测试了服务器逻辑。
服务器测试(按预期方式工作):
const http = app.listen(4001,function () {
console.log('api listening on',4001);
});
new Chat(http);
beforeEach((done) => {
client = io.connect('http://localhost:4001',{
'reconnection delay': 0,'reopen delay': 0,'force new connection': true,transports: ['websocket'],});
client.on('connect',() => {
console.log('connected');
done();
});
...
});
afterEach((done) => {
if (client.connected) {
client.disconnect();
}
done();
});
it('should login',(done) => {
client.emit(ChatEvents.LOGIN,{ userId });
client.on(ChatEvents.LOGGED_IN,async () => {
const user = await User.findById(userId);
expect(user.socketId).not.to.be.an('undefined');
done();
});
});
...
客户:
我想测试客户端逻辑(React),但是我不确定如何从测试中调用socket.on。
import io from 'socket.io-client';
export const socket = io();
socket.on(ChatEvents.SEND_ALL_CHATS_TO_SENDER,({chats}) => {
if (isAuthenticated()) {
console.log(ChatEvents.SEND_ALL_CHATS_TO_SENDER,chats);
setChats(chats);
updateScroll();
}
});
是否可以从测试中调用它并将其发送给模拟数据,或者是否可以设置模拟socket.io服务器并发出数据?
我尝试了mock-socket和其他类似的库,并在测试中发出并监听了这些库,但是这些库未调用组件中的套接字。
测试:
import { mount } from 'enzyme';
import React from 'react';
import { Chats } from './Chats';
describe('Chats',() => {
function renderComponent(args?) {
const defaultProps = {
userId: '',chats: [],setChatActiveStatus: jest.fn(),setChats: jest.fn(),resetChats: jest.fn(),addChat: jest.fn(),updateChat: jest.fn(),setUserTyping: jest.fn(),};
const props = { ...defaultProps,...args };
return mount(<Chats {...props} />);
}
beforeEach(() => {});
it('should update the chats',async () => {
const wrapper = renderComponent();
// invoke socket.on?
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。