【问题标题】:Testing with Mocha in Node.js在 Node.js 中使用 Mocha 进行测试
【发布时间】:2023-03-08 22:06:01
【问题描述】:

在我使用 mocha 编写的测试中进行 console.logging 时,我的终端出现了非常不一致的行为。我们正在运行 node.js 服务器并运行 socket.io。出于某种原因,console.log 是否仅在某些时候不进入终端?我真的对这种行为感到困惑。

➜  tests git:(master) ✗ mocha test-chat-server.js
hello world


echo
✓ echos message (68ms)

On Connect Things Should Happen
✓ initial connection events
  disconnected
  i'm here


    2 passing (93ms)

➜  tests git:(master) ✗ mocha test-chat-server.js
  hello world


    echo
      ✓ echos message (61ms)

    On Connect Things Should Happen
      ✓ initial connection events


    2 passing (77ms)

这两次我运行 mocha 测试的区别在于第一次测试运行中出现的 console.log 语句(断开连接,我在这里)。它们没有出现在我运行的第二个测试中。

编辑:发布我的测试代码以回应评论(谢谢!)

var should = require('should');
var socket = require('socket.io-client')('http://localhost:3000');


describe("echo", function () {
    var server,
        options ={
            transports: ['websocket'],
            'force new connection': true
        };

    it("echos message", function (done) {
        var client = socket.connect("http://localhost:3000", options);

        client.once("connect", function () {
            client.once("echo", function (message) {
                message.should.equal("Hello World");

                client.disconnect();
                done();
            });

            client.emit("echo", "Hello World");
        });
        done();
    });
});

describe("On Connect Things Should Happen", function() {

    it('initial connection events', function() {

        should.exist(socket); 
        socket.open();      
        socket.compress(false).emit('an event', { some: 'data' });

        socket.on('error', function() {
            console.log('error'); 
        }); 

        socket.connect(); 
        socket.on('disconnect', function(connection) {
            console.log('disconnected'); 
            console.log("i'm here");
        });



        socket.on('connect', function(connection) {
            console.log('connected'); 
        });
    });
});

【问题讨论】:

  • 请发布您的测试代码。
  • 对不起!我已经发过了

标签: node.js unit-testing socket.io mocha.js


【解决方案1】:

您陷入了经典的节点异步陷阱。您的“事情应该发生”测试有时会在断开事件发生之前返回,有时不会。

您需要像在“回显消息”测试中一样处理完成功能。准时,它应该是这样的:

socket.on('disconnect', function(connection) { 
console.log('disconnected'); 
console.log("i'm here"); 
done()});

一般来说,我不确定该测试对处理所有这些不同的回调有多大影响。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-13
    • 2017-10-26
    • 2017-08-03
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多