应该使用哪种方法来使用Jest测试SocketIO客户端应用程序?

时间:2019-10-21 10:39:35

标签: reactjs socket.io jestjs enzyme

我需要使用SocketIO Client测试React Client应用。我已经在网上搜索了各种网站,但找不到任何示例。然后,我以开发者依赖项的形式在客户端应用程序上安装了Express,并尝试在Jest测试中启动测试服务器,但无法正常工作。

所以我想知道,实际上,无论如何,测试该应用程序的正确方法是什么?

我的目标是测试在componentDidMount中注册的以下事件侦听器

componentDidMount() {
    const current_this = this;
    socket.on("numOfPlayersChanged", function(data) {
      // do something
    });
  }

1 个答案:

答案 0 :(得分:1)

这是我的解决方法:

index.tsx

import React, { Component } from 'react';
import io from 'socket.io';

const socket = io();

class SomeComponent extends Component {
  constructor(props) {
    super(props);
    this.handleNumOfPlayersChanged = this.handleNumOfPlayersChanged.bind(this);
  }
  componentDidMount() {
    socket.on('numOfPlayersChanged', this.handleNumOfPlayersChanged);
  }
  render() {
    return <div>some component</div>;
  }

  handleNumOfPlayersChanged() {
    console.log('do something');
  }
}

export default SomeComponent;

index.spec.tsx

import React from 'react';
import SomeComponent from './';
import { shallow } from 'enzyme';
import io from 'socket.io';

jest.mock('socket.io', () => {
  const mSocket = {
    on: jest.fn()
  };
  return jest.fn(() => mSocket);
});

describe('SomeComponent', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = shallow(<SomeComponent></SomeComponent>);
    jest.restoreAllMocks();
  });
  test('should mount component and register socket event', () => {
    const instance = wrapper.instance() as any;
    const mSocket = io();
    expect(wrapper.text()).toBe('some component');
    expect(mSocket.on).toBeCalledWith('numOfPlayersChanged', instance.handleNumOfPlayersChanged);
  });

  test('should handle player changed ', () => {
    const logSpy = jest.spyOn(console, 'log');
    const instance = wrapper.instance() as any;
    instance.handleNumOfPlayersChanged();
    expect(logSpy).toBeCalledWith('do something');
  });
});

覆盖率100%的单元测试结果:

 PASS  src/stackoverflow/58484558/index.spec.tsx
  SomeComponent
    ✓ should mount component and register socket event (10ms)
    ✓ should handle player changed  (7ms)

  console.log node_modules/jest-mock/build/index.js:860
    do something

-----------|----------|----------|----------|----------|-------------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files  |      100 |      100 |      100 |      100 |                   |
 index.tsx |      100 |      100 |      100 |      100 |                   |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.62s, estimated 8s

源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58484558