unit testing - How to test node.js websocket server with mocha? -
i need test poker game server, based on websocket.
so, if player1
send message server, server should send message other players.
i write test block below:
describe('protocol', () => { before(() => { player1 = new websocket('ws://xxxxxx'); player1 = new websocket('ws://xxxxxx'); player2 = new websocket('ws://xxxxxx'); player3 = new websocket('ws://xxxxxx'); }); it('player1 send message1 player3 should receive' (done) => { //block1 let message1 = { id: 'message1', data: 'message1' }; player1.send(json.stringify(message1)); player3.once('message', (message) => { //block2 expect(message).equal(json.stringify(message1)), done(); }); }); it('player2 send message2 player3 should receive' (done) => { //block3 let message2 = { id: 'message2', data: 'message2' }; player2.send(json.stringify(message1)); player3.once('message', (message) => { //block4 expect(message).equal(json.stringify(message2)), done(); }); }); }
the order of execution want : block1
-> block2
-> block3
-> block4
but truly:blocks1
-> block3
-> block2
-> block4
so message
of block4
message1
instead of message2
how can solve problem?
simply answer move playerx.send(messagex);
after playerx.once()
, that's it.
just in mind, these call async, order not important, need ready receive before fire something.
describe('protocol', () => { before(() => { player1 = new websocket('ws://xxxxxx'); player1 = new websocket('ws://xxxxxx'); player2 = new websocket('ws://xxxxxx'); player3 = new websocket('ws://xxxxxx'); }); it('player1 send message1 player3 should receive', (done) => { //block1 let message1 = { id: 'message1', data: 'message1' }; player3.once('message', (message) => { //block2 expect(message).equal(json.stringify(message1)); done(); }); player1.send(json.stringify(message1)); }); it('player2 send message2 player3 should receive', (done) => { //block3 let message2 = { id: 'message2', data: 'message2' }; player3.once('message', (message) => { //block4 expect(message).equal(json.stringify(message2)); done(); }); }); player2.send(json.stringify(message1)); }
Comments
Post a Comment