我想用Jest对这个JS代码进行单元测试。它使用的是ws WebSocket库:
Socket.js
import WebSocket from "ws";
export default class Socket {
socket = undefined;
connect(url): void {
if (this.socket !== undefined && this.socket.readyState === WebSocket.OPEN) {
throw new Error("Socket is already connected");
}
this.socket = new WebSocket(url);
}
}
我想检查是否抛出了错误。为此,我为套接字创建了一个模拟,然后需要将套接字对象的readyState
设置为CLOSED
。问题是这是不可能的,因为它是一个只读字段。
测试项目:
import Socket from "./Socket";
import WebSocket from "ws";
jest.mock("ws");
it("can connect", () => {
// Arrange
const url = "www.someurl.com";
jest.spyOn(global, "Promise").mockReturnValueOnce({} as Promise<void>);
const sut = new Socket();
// Act
sut.connect(url);
const webSocket = jest.mocked(WebSocket).mock.instances[0];
// Set readystate of socket
webSocket.readyState = WebSocket.CLOSED; // Error here: Cannot assign to 'readyState' because it is a read-only property. ts(2540)
const action = () => sut.connect(url);
// Assert
expect(action).toThrowError(new Error("Socket is already connected"));
});
问题:如何在socket.readyState
等库的模拟上测试使用只读字段的代码?
**编辑:**根据上述要求添加了mvce。
1条答案
按热度按时间x33g5p2x1#
更好的测试策略是创建一个测试WebSocket服务器并连接它。这也是官方团队正在做的,请参见一些测试用例。不建议模拟
ws
并测试实现细节。下面使用TypeScript测试代码:
socket.ts
:socket.test.ts
:检测结果:
软件包版本: