如何编写我的代码来测试 websocket 事件?

How to write my code to test a websocket event?

我正在尝试测试在 websocket 事件触发后数据是否被添加到我的数据库中。

在我正在使用的应用程序中,已经有一个这样的工作示例。

it('some test name', function (done) {
    this.timeout(12000)

    var socket = io.connect('http://localhost:3000', {
      'transports': [
        'websocket',
        'flashsocket',
        'jsonp-polling',
        'xhr-polling',
        'htmlfile'
      ]
    })

    socket.emit('some-room-event', {
      participant: 'p1',
      room: 12,
      active: true
    })

    setTimeout(function () {
      app.service('rooms').get(12)
         .then(function (room) {
           assert(room.active === true)
           socket.disconnect()
           done()
         }).catch(function (err) {
           socket.disconnect()
           done(err)
         })
    }, 11000)
  })

我来自 ruby 背景并进入该项目,所以我很新。感觉有点像使用超时是一种代码味道,感觉不对。您不想通过任意等待时间来增加 运行 测试所需的持续时间。

我已经阅读了很多关于此的文章,但它非常令人困惑。有没有更好的方法来构建此代码并可能摆脱 setTimeout?

我正在使用 feathersjs、mocha 和 assert。

看起来正在测试的事件只是对 rooms 服务执行某些操作的普通 websocket 事件。

测试中的任意超时绝对不是解决websocket事件在完成它应该做的事情时不确认的问题的最佳方法。我认为你可以做的是在房间为 updatedpatched 时收听 a Feathers service event (尽管有点奇怪,套接字事件不只是使用官方 socket.emit('rooms::update', data) 更新房间状态):

it('some test name', function (done) {
  var socket = io.connect('http://localhost:3000', {
    'transports': [
      'websocket',
      'flashsocket',
      'jsonp-polling',
      'xhr-polling',
      'htmlfile'
    ]
  });

  app.service('rooms').once('updated', function(room) {
    assert(room.active);
    done();
  });

  socket.emit('some-room-event', {
    participant: 'p1',
    room: 12,
    active: true
  });
});