2017-05-24 127 views
0

我正在嘗試測試事件篩選器,但是存在一個我不確定如何解決的計時問題。除了在setTimeout中包裝REST請求之外,我怎麼能得到這個工作?如何知道羽毛客戶端何時連接到服務

const app = require('../../src/app'); 

const feathers = require('feathers/client') 
const socketio = require('feathers-socketio/client'); 
const hooks = require('feathers-hooks'); 
const io = require('socket.io-client'); 

const rp = require('request-promise'); 

const service = app.service('users'); 

let server = null; 

describe('\'users\' service',() => { 
    beforeEach((done) => { 
    server = app.listen('3030'); 
    server.once('listening', done); 
    }); 

    afterEach((done) => { 
    server.close(done); 
    }); 

    it('returns stuff #test', (done) => { 
    const socket = io('http://localhost:3030'); 
    const app = feathers() 
     .configure(hooks()) 
     .configure(socketio(socket)); 

    const messageService = app.service('users'); 
    messageService.on('created', message => { 
     console.log('Created a message', message); 
     done(); 
    }); 

    socket.on('connection',() => { 
     // 
     // The messageService is not connected yet 
     // so messages.filters.js will not fire 
     // 
     // Giving it a chance to connect with setTimeout does work... 
     //   setTimeout(() => { 
     rp({ 
      method: 'POST', 
      url: 'http://localhost:3030/users', 
      body: { 
      test: 'Message from REST' 
      }, 
      json: true 
     }); 
     //   }, 500); 
    }); 

    }); 
}); 

我曾嘗試更換socket.on這些還有:

  • messageService.on('connection'
  • service.on('connection'(基於Node.js的EventEmitter)
  • 等等...

編輯

我自那時以來發現service.on('newListener'工作,但它被觸發很多次。我需要追蹤單個連接:

const messageService = app.service('users'); 
messageService.on('created', message => { 
    console.log('Created a message', message); 
    done(); 
}); 

回答

0

這簡直就是service.on('newListener'。爲「器newListener」事件註冊

https://nodejs.org/api/events.html#events_event_newlistener

聽衆將被傳遞的事件名稱和到聽衆的引用被添加。

但是,當我實現這個時,我發現它正在監聽5個不同的事件。所以,你需要將它們過濾掉:

service.on('newListener', (event, listener) => { 
    if (event === 'created') { 
    rp({ 
     method: 'POST', 
     url: 'http://localhost:3030/users', 
     body: { 
     test: 'Message from REST' 
     }, 
     json: true 
    }); 
    } 
}); 
相關問題