栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

单元测试Node.js和WebSockets(Socket.io)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单元测试Node.js和WebSockets(Socket.io)

经过进一步的摸索和探索,我发现了一些非常有用的信息。在作者的示例中,他指出了在

before

钩子中建立套接字侦听器的关键步骤。

此示例有效:

假设一个服务器监听的套接字连接

localhost: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()
beforeEach
socket.on('connect'...)
监听器是具有连接得到建立至关重要。例如,如果您
done()
在侦听器中将其注释掉,然后将其添加到一个作用域中(
就在退出之前
beforeEach
),则会看到 “ no connection to break …” 消息,而不是
disconnecting …”
消息。像这样:

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();});

我是Mocha的新手,因此可能有一个很明显的原因要让启动程序放置

done()
在套接字作用域本身内。希望这个小细节可以省掉我的鞋子中的其他头发。

对我来说,上述测试( 正确设定范围

done()
)输出:

  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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/427047.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号