如何使用Jest/React-Testing-Library模拟socket.io-client [英] How to mock socket.io-client using jest/react-testing-library

查看:84
本文介绍了如何使用Jest/React-Testing-Library模拟socket.io-client的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个聊天应用程序,并且想使用react-testing-library编写集成测试,并且无法弄清楚如何模拟socket.io-clientsocket.onsocket.emit等.

我尝试遵循文章,并尝试使用 mock-socket.io socket.io-mock 都没有运气. >

这是我要测试的组件:

 import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import 'dotenv/config';
import ChatInput from './ChatInput';
import Messages from './Messages';

function App() {
  const [messages, setMessages] = useState([]);

  const port = process.env.REACT_APP_SERVER_PORT;
  const socket = io(`http://localhost:${port}`);

  useEffect(() => {
    socket
      .emit('app:load', messageData => {
        setMessages(messages => [...messages, ...messageData]);
      })
      .on('message:new', newMessage => {
        setMessages(messages => [...messages, newMessage]);
      });
  }, []);

  const postMessage = input => {
    socket.emit('message:post', input);
  };

  return (
    <div className="App">
      <Messages messages={messages} />
      <ChatInput postMessage={postMessage} />
    </div>
  );
}

export default App;
 

解决方案

这是一个较晚的答案,但可能对其他人有用:

模拟socket.io-client库我使用了笑话模拟函数并使用了第三方库socket.io-mock article and tried using mock-socket.io and socket.io-mock all with no luck.

This is the component I am trying to test:

import React, { useEffect, useState } from 'react';
import io from 'socket.io-client';
import 'dotenv/config';
import ChatInput from './ChatInput';
import Messages from './Messages';

function App() {
  const [messages, setMessages] = useState([]);

  const port = process.env.REACT_APP_SERVER_PORT;
  const socket = io(`http://localhost:${port}`);

  useEffect(() => {
    socket
      .emit('app:load', messageData => {
        setMessages(messages => [...messages, ...messageData]);
      })
      .on('message:new', newMessage => {
        setMessages(messages => [...messages, newMessage]);
      });
  }, []);

  const postMessage = input => {
    socket.emit('message:post', input);
  };

  return (
    <div className="App">
      <Messages messages={messages} />
      <ChatInput postMessage={postMessage} />
    </div>
  );
}

export default App;

解决方案

This is a late answer but maybe useful for others:

to mock socket.io-client library I used jest mock function and used a third party library socket.io-mock https://www.npmjs.com/package/socket.io-mock

You need to modify your connection function as follows in order to work with mocked socket:

const url= process.env.NODE_ENV==='test'?'':`http://localhost:${port}`;
const socket = io(url);

Implementation:

import socketIOClient from 'socket.io-client';
import MockedSocket from 'socket.io-mock';

jest.mock('socket.io-client');

describe('Testing connection', () => {
  let socket;

  beforeEach(() => {
    socket = new MockedSocket();
    socketIOClient.mockReturnValue(socket);
  });

  afterEach(() => {
    jest.restoreAllMocks();
  });

  it('should dispatch connect event', () => {
    /*socket should connect in App and 
    Note that the url should be dummy string 
    for test environment e.g.(const socket = io('', options);)*/
    const wrapper = (
      <Provider store={store}>
        <App />
      </Provider>
    );

    expect(socketIOClient.connect).toHaveBeenCalled();
  });

  it('should emit message:new', done  => {
    const wrapper = (
      <Provider store={store}>
        <App />
      </Provider>
    );
    ...
    socket.on('message:new', (data)=>{
        expect(data).toEqual(['message1', 'message2']);
        done();
    });

    socket.socketClient.emit('message:new', ['message1', 'message2']);
    ...
  });
});

这篇关于如何使用Jest/React-Testing-Library模拟socket.io-client的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆