gpt4 book ai didi

javascript - javascript中网络套接字的单元测试

转载 作者:行者123 更新时间:2023-11-29 15:41:57 27 4
gpt4 key购买 nike

我需要使用 sinon 为 Web 套接字客户端编写单元测试。代码如下:

Socket = {
connect: function ()
{
socket = new WebSocket('ws://localhost:12345');
socket.onopen = function()
{

console.log('connected to the server');
};

socket.onmessage = function(message)
{
console.log('Received:', message.data);
};

}
};

最佳答案

我们最后需要在connect 方法中返回socket 实例。因为您为 onopenonmessage 事件分配了两个新函数。它将覆盖套接字对象上的 spystub 方法。

测试环境:节点

这是单元测试解决方案:

index.js:

const Socket = {
connect: function() {
socket = new WebSocket("ws://localhost:12345");
socket.onopen = function() {
console.log("connected to the server");
};

socket.onmessage = function(message) {
console.log("Received:", message.data);
};
return socket;
}
};

module.exports = Socket;

index.spec.js:

const sinon = require("sinon");
const { expect } = require("chai");
const Socket = require("./index");

class WebSocket {
constructor(uri) {}
onopen() {}
onmessage() {}
}
global.WebSocket = WebSocket;

describe("17806481", () => {
it("should test connect correctly", () => {
const logSpy = sinon.spy(console, "log");
const socket = Socket.connect();
const onopenSpy = sinon.spy(socket, "onopen");
const onmessageSpy = sinon.spy(socket, "onmessage");
onopenSpy();
expect(logSpy.firstCall.calledWith("connected to the server")).to.be.true;
const mMessage = { data: "fake data" };
onmessageSpy(mMessage);
expect(logSpy.secondCall.calledWith("Received:", mMessage.data)).to.be.true;
});
});

Socket 模块 100% 覆盖率的单元测试结果:

 17806481
connected to the server
Received: fake data
✓ should test connect correctly


1 passing (10ms)

---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 75 | 100 | |
index.js | 100 | 100 | 100 | 100 | |
index.spec.js | 100 | 100 | 60 | 100 | |
---------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/17806481

关于javascript - javascript中网络套接字的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17806481/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com