さらに突っ込んで突き刺した後、私はhttp://blog.foundry376.com/2012/09/connecting-to-a-socket-io-server-from-node-js-unit-testsに信じられないほど役に立つ情報を見つけました。著者の例では、 "before *"フックにソケットリスナーを確立するための重要なステップを指摘しています。私はbeforeEach、socket.on(「接続」内)(済の配置ことがわかった。(もちろん、3001サーバがローカルホストのソケット接続を待機していると仮定した場合)
var io = require('socket.io-client')
, assert = require('assert')
, expect = require('expect.js');
describe('Suite of unit tests', function() {
var socket;
beforeEach(function(done) {
// Setup
socket = io.connect('http://localhost:3001', {
'reconnection delay' : 0
, 'reopen delay' : 0
, 'force new connection' : true
});
socket.on('connect', function() {
console.log('worked...');
done();
});
socket.on('disconnect', function() {
console.log('disconnected...');
})
});
afterEach(function(done) {
// Cleanup
if(socket.connected) {
console.log('disconnecting...');
socket.disconnect();
} else {
// There will not be a connection unless you have done() in beforeEach, socket.on('connect'...)
console.log('no connection to break...');
}
done();
});
describe('First (hopefully useful) test', function() {
it('Doing some things with indexOf()', function(done) {
expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
done();
});
it('Doing something else with indexOf()', function(done) {
expect([1, 2, 3].indexOf(5)).to.be.equal(-1);
expect([1, 2, 3].indexOf(0)).to.be.equal(-1);
done();
});
});
});
を...この例では動作します)リスナーは、接続を確立するために非常に重要でした。たとえば、リスナーでdone()をコメントアウトしてから、スコープを1つ追加すると(beforeEachを終了する直前)、「切断しています...」の代わりに「no connection to break ...」というメッセージが表示されます。 "メッセージ。これと同じように:
beforeEach(function(done) {
// Setup
socket = io.connect('http://localhost:3001', {
'reconnection delay' : 0
, 'reopen delay' : 0
, 'force new connection' : true
});
socket.on('connect', function() {
console.log('worked...');
//done();
});
socket.on('disconnect', function() {
console.log('disconnected...');
});
done();
});
私はモカに新たなんだ、これは非常に明白な理由は、ソケットスコープ自体withiin()で行わ置くための開始におそらくあります。その細かいディテールが、私の靴の中の他人を髪を引っ張って救うことを望みます。
は私にとっては、上記のテストは、出力(完了()の正しいスコープで):
Suite of unit tests
First (hopefully useful) test
◦ Doing some things with indexOf(): worked...
✓ Doing some things with indexOf()
disconnecting...
disconnected...
◦ Doing something else with indexOf(): worked...
✓ Doing something else with indexOf()
disconnecting...
disconnected...
2 tests complete (93 ms)
このモカまたはジャスミンのテストはありますか?非同期のモカテスト(これはこれです)の場合、テスト関数はコールバック 'function(testDone)'を呼び出す必要があります。そのため、モカはそれを適切に処理することを認識しています。これは実際には動作しているかもしれませんが、mochaは待機する必要があることを知らないため、 'connect'イベントが発生する前にmochaが終了しています。 –