【问题标题】:How to test websocket with jest and enzyme?如何用 jest 和酵素测试 websocket?
【发布时间】:2023-04-10 04:13:01
【问题描述】:

我正在构建一个 web 应用程序并希望对其进行单元测试。它还具有 Socket.io websocket 后端(expressjs 后端)和 react 应用程序上的 socket.io 客户端,它是 create-react-app 应用程序。 这是到目前为止的测试:

import React from 'react';

// 3rd party imports 
import { render } from '@testing-library/react';
import { shallow, mount } from "enzyme";
import { SocketIO, Server } from 'mock-socket';

// custom imports
import App from '../App';
import Tasks from '../components/Tasks';

describe('App', () => {
  let wrapper, shallowWrapper;
  const mockServer = new Server('ws://localhost:8080');
  window.io = SocketIO;
  beforeEach(async () => {
    wrapper = mount(<App />);
    //start web socket config with mock-server
    mockServer.on('connection', socket => {
      socket.emit('task', 'test message from mock server');
    });
  // end web socket config
    shallowWrapper = shallow(<App />);
  });

  it("renders", () => {
    shallow(<App />);
  });

  test('renders right text', () => {
    const { getByText } = render(<App />);
    const linkElement = getByText(/BI4 Monitor/i);
    expect(linkElement).toBeInTheDocument();
  });

  it('has one unordered list', () =>{
    expect(wrapper.find("ul")).toHaveLength(0);
  });

  it("displays initial empty list", () => {
    expect(wrapper.find("li")).toHaveLength(0);
  });

  it("has Tasks component", () => {
    console.log(shallowWrapper.debug())
    expect(shallowWrapper.contains(<Tasks/>)).toBe(true);
  });

});

我正在使用这个模拟库: https://github.com/thoov/mock-socket

这里是 App.js

import React, { useEffect, useState } from 'react';

// 3rd party imports
import Container from 'react-bootstrap/Container';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';
import { useImmer } from 'use-immer';
import _ from "underscore";

// custom imports
import { SocketUtil } from './utils';
import Tasks from './components/Tasks';

const socket = SocketUtil.init();

function App() {
  const [msg, setMsg] = useState([]);
  function handleData(payload) {
    // data = [...data, payload]
    setMsg(m => m.concat(payload));
  }

  useEffect(() => {
     socket.on('task', payload => {
       console.log("taskkkk")
       handleData(payload);
     });
  });


  return (
    <Container>
      <Row className="row">
        <Col xs={12}>
          <h1>BI4 Monitor</h1>
          {/* <Tasks/> */}
          {_.map(msg, function(m) {
            return (
              <p>{m.key}</p>
            );
          })}
          <Tasks/>
        </Col>
      </Row>
    </Container>
  );
}

export default App;

我希望打印 console.log("taskkkk") 或基本上只是单元测试以查看不止一个 &lt;p&gt;{m.key}&lt;/p&gt; 被渲染但没有发生。 我也试过https://github.com/romgain/jest-websocket-mock,但没有运气。 有什么想法可以实现吗?

【问题讨论】:

  • 1) 您的应用程序是否按预期工作?但不是测试?说您的问题是“为什么模拟不起作用”是否正确?还是更多?目前还不清楚。 2) 什么是SocketUtil.init()?显示代码。 3) 测试“看到不止一个&lt;p&gt;{m.key}&lt;/p&gt; 被渲染”在哪里? 4)it('has one unordered list ... .toHaveLength(0)你确定length = 0,顾名思义是1? 5) 从问题中删除不相关的 cmets 和测试。例如{/* &lt;Tasks/&gt; */} ...或者它应该是&lt;Tasks&gt;...&lt;/Tasks&gt;,在这种情况下 - 修复它。
  • 6) 可能需要&lt;Task&gt; 的代码。 7) Github 有一个最小的可重现示例 - 是要走的路

标签: unit-testing websocket socket.io jestjs enzyme


【解决方案1】:

我只是尝试自己模拟 WebSocket JS API。请参考这里https://stackoverflow.com/a/68579278/4124267

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2020-08-12
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2021-11-22
    • 1970-01-01
    • 2018-12-16
    相关资源
    最近更新 更多