How to mock socket.io-client using jest/react-testing-library

北战南征 提交于 2020-05-16 03:11:30

问题


I am building a chat app and would like to write integration tests using react-testing-library and can not figure out how to mock socket.io-client's socket.on, socket.emit, etc.

I tried follow this 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;

回答1:


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


来源:https://stackoverflow.com/questions/58211676/how-to-mock-socket-io-client-using-jest-react-testing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!