在Sails.js应用程序中为Mocha测试创建WebSocket客户端?

时间:2017-03-28 12:41:54

标签: javascript node.js socket.io sails.js mocha

我试图在我的Sails JS应用程序的Mocha测试中使用socket.io-client进行如下调用。但是,.get / .post不会被调用,测试用例会超时。

var io = require('socket.io-client');
io.sails.url = sails.getBaseUrl();

// This doesn't work
io.socket.get('/hello', function serverResponded (body, JWR) {
  console.log('Sails responded with: ', body);
  console.log('with headers: ', JWR.headers);
  console.log('and with status code: ', JWR.statusCode);
  io.socket.disconnect();

});

1 个答案:

答案 0 :(得分:0)

看起来你很混淆socket.io-client,它是低级别的Socket.io客户端库,带有sails.io.js,它是Sails.js实用程序,用于通过套接字与Sails应用程序通信。请查看sails.io.js README以获取有关如何从节点使用Sails套接字客户端的说明:

var socketIOClient = require('socket.io-client');
var sailsIOClient = require('sails.io.js');

// Instantiate the socket client (`io`)
// (for now, you must explicitly pass in the socket.io client when using this library from Node.js)
var io = sailsIOClient(socketIOClient);

// Set some options:
// (you have to specify the host and port of the Sails backend when using this library from Node.js)
io.sails.url = 'http://localhost:1337';
// ...

// Send a GET request to `http://localhost:1337/hello`:
io.socket.get('/hello', function serverResponded (body, JWR) {
  // body === JWR.body
  console.log('Sails responded with: ', body);
  console.log('with headers: ', JWR.headers);
  console.log('and with status code: ', JWR.statusCode);

  // ...
  // more stuff
  // ...


  // When you are finished with `io.socket`, or any other sockets you connect manually,
  // you should make sure and disconnect them, e.g.:
  io.socket.disconnect();

  // (note that there is no callback argument to the `.disconnect` method)
});