如何使用 jest/react-testing-library 模拟 socket.io-client

IT技术 reactjs socket.io jestjs react-hooks react-testing-library
2021-05-07 15:42:32

我建立一个聊天应用程序,并会使用喜欢写集成测试react-testing-library并不能弄清楚如何嘲笑socket.io-clientsocket.onsocket.emit等等。

我尝试按照这篇文章并尝试使用mock-socket.iosocket.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;
1个回答

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

模拟socket.io-client库我使用了 jest 模拟函数并使用了第三方库socket.io-mock https://www.npmjs.com/package/socket.io-mock

您需要按如下方式修改连接函数才能使用模拟套接字:

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

执行:

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']);
    ...
  });
});