测试socket.io服务器返回假肯定

时间:2018-12-03 11:20:32

标签: unit-testing testing socket.io jestjs

我正在使用jest为node / socket.io应用程序设置测试套件。

当我测试服务器->客户端通信时,一切正常。

当我测试客户端->服务器通信时,我的测试套件通过了误报:

这是产生误报的测试:

test('should communicate with waiting for socket.io handshakes', (done) => {
        client.emit('example', 'some message');
        setTimeout(() => {
          server.on('example', (message) => {
            expect(message).toBe('some message')
          })
          done();
        }, 50);
      });

这是我的整个测试套件:

import io from 'socket.io-client';
import * as http from 'http';
import ioBack from 'socket.io';

let client;
let httpServer;
let httpServerAddr;
let server;

/**
 * Setup WS & HTTP servers
 */
beforeAll((done) => {
  httpServer = http.createServer().listen();
  httpServerAddr = httpServer.address();
  server = ioBack(httpServer);
  done();
});


/**
 *  Cleanup WS & HTTP servers
 */
afterAll((done) => {
  server.close();
  httpServer.close();
  done();
});

/**
 * Run before each test
 */
beforeEach((done) => {
  // Setup
  // Do not hardcode server port and address, square brackets are used for IPv6
  client = io.connect(`http://[${httpServerAddr.address}]:${httpServerAddr.port}`, {
    'reconnection delay': 0,
    'reopen delay': 0,
    'force new connection': true,
    transports: ['websocket'],
  });
  client.on('connect', () => {
    done();
  });
});

/**
 * Run after each test
 */
afterEach((done) => {
  // Cleanup
  if (client.connected) {
    client.disconnect();
  }
  done();
});


describe('basic socket.io example', () => {
  test('should communicate', (done) => {
    // once connected, emit Hello World
    server.emit('echo', 'Hello World');
    client.on('echo', (message) => {
      // Check that the message matches
      expect(message).toBe('Hello World');
      done();
    });
    server.on('connection', (mySocket) => {
      expect(mySocket).toBeDefined();
    });
  });
  test('should communicate with waiting for socket.io handshakes', (done) => {
    client.emit('example', 'some message');
    setTimeout(() => {
      server.on('example', (message) => {
        expect(message).toBe('some  incorrect message')
      })
      done();
    }, 50);
  });
});

我不确定为什么我会得到误报。

0 个答案:

没有答案