Best JavaScript code snippet using cypress
comms.js
Source:comms.js
1// websockets broker, derived from https://www.npmjs.com/package/wsbroker2// but with many features removed (in particular, JSON, matching, and back end support)3var log, hostname;4var Broker = function (config) {5 const broker = this;6 if (!require) return;7 const Http = require('http');8 const WebSocketServer = require('ws').Server;9 /** function called when client closed, will callback if specificed */10 function onWSClose(connection) {11 broker.log('â connection closed', connection.wskey);12 if (broker.config.onClientDisconnect)13 broker.config.onClientDisconnect(connection, broker);14 broadcast(clients(['!left', connection.wskey, '!clients']));15 }16 /** broadcast message. if fromwskey is specified do not send to that key */17 function broadcast(message, fromwskey) {18 if (Array.isArray(message)) message = message.join(Broker.splitter);19 const recipients = [];20 websocketServer.clients.forEach(function (toconnection) {21 if (toconnection.wskey !== fromwskey) {22 sendClientMessage(toconnection, message);23 recipients.push(toconnection);24 }25 });26 broker.log('â sent to ' + (recipients.length) + '/' + (websocketServer.clients.length) + ' clients', message);27 }28 /** function called when client message arrives, process as broker message (!...) or callback */29 function onClientMessage(fromconnection, message) {30 broker.log('â from client', fromconnection.wskey, message);31 if (message[0] === '!')32 handleBrokerMessage(fromconnection, message);33 if (broker.config.onClientMessage)34 broker.config.onClientMessage(message, fromconnection, broker);35 }36 /** handle special message (first char !) at broker */37 function handleBrokerMessage(fromconnection, message) {38 const mm = message.split(Broker.splitter);39 switch (mm[0]) {40 case '!clients':41 sendClientMessage(fromconnection, clients(['!clients']));42 break;43 default:44 log('unexpected broker message ignored:', message);45 sendClientMessage(fromconnection, message + ' UNEXPECTEDMESSAGE');46 break;47 }48 }49 /** return array of clients, prepended by other details */50 function clients(pre = []) {51 websocketServer.clients.forEach( (c) => pre.push(c.wskey) )52 return pre;53 }54 /* send message to specific client, message may be string or array */55 function sendClientMessage(toconnection, message) {56 if (Array.isArray(message)) message = message.join(Broker.splitter);57 // if (typeof message === 'object') message =58 try {59 toconnection.send(message);60 broker.log('â to client', toconnection.wskey, message);61 } catch (ee) { broker.log('failed to send message to client', toconnection.wskey)}62 }63 broker.sendClientMessage = sendClientMessage;64 /** function called when new client connects */65 function onWSConnection(connection) {66 try {67 connection.broker = broker;68 connection.wskey = [onWSConnection.id++, hostname, Date.now()].join('_');69 broker.log('⪠new connection', connection.wskey);70 connection.on('message', function (message) { onClientMessage(connection, message); });71 connection.on('close', function () { onWSClose(connection); });72 broker.broadcast(clients(['!join', connection.wskey, '!clients']));73 if (broker.config.onClientConnect)74 broker.config.onClientConnect(connection);75 } catch (ee) {76 broker.log('! Connection Error', ee);77 }78 }79 onWSConnection.id = 1;80 function initWebSocketServer() {81 const server = Http.createServer();82 const wsrv = new WebSocketServer({server});83 wsrv.on('connection', onWSConnection);84 wsrv.on('error', (error) => broker.log('websocket server error: ', error));85 server.listen(broker.config.port, () => {86 broker.status = 'ready';87 broker.log('⥠websocket server listening on port ' + broker.config.port);88 });89 return (wsrv);90 }91 broker.config = config;92 broker.broadcast = broadcast;93 broker.log = broker.config.log || (()=>{}); // can be overridden later94 const websocketServer = initWebSocketServer();95}96Broker.splitter = '\t'; // for parsing broker messages97//// easy initial test98/**99var broker = new Broker({100 port: 12345,101 // log, // could be nop, or not defined, or some other function102 onClientMessage: function (message, connection, broker) {103 log('MESSAGE RECEIVED!', message);104 broker.broadcast(message);105 }106});107var log, WebSocket;108var wss1 = new WebSocket('ws://localhost:12345'); // var for test, we may want to redefine109var wss2 = new WebSocket('ws://localhost:12345'); // var for test, we may want to redefine110wss1.onmessage = (msg) => log('wss1 in', msg.data);111wss2.onmessage = (msg) => log('wss2 in', msg.data);112setTimeout(() => wss1.send('test'), 3000)...
server.js
Source:server.js
...61 debug('got http request');62 res.writeHead(200, {Connection: 'close'});63 res.end('LiveStyle WebSocket server is up and running by LiveStyle App.');64}65function onWsConnection(conn) {66 debug('received ws connection');67 clients.push(conn);68 conn69 .on('message', handleMessage)70 .on('close', removeClient);71 sendMessage(clients, {name: 'client-connect'}, conn);72}73function onServerClose() {74 debug('closed');75 if (this.ws) {76 this.ws.removeListener('connection', onWsConnection);77 this.ws = null;78 }79}...
RestBrokerServer.js
Source:RestBrokerServer.js
1const http=require("http");2const WebSocket=require("ws");3const ServerConnection=require("./ServerConnection");4const url=require("url");5const EventEmitter=require("events");6const restbrokerPackage=require("../package.json");7class RestBrokerServer extends EventEmitter {8 constructor() {9 super();10 this.httpServer=http.createServer(this.onHttpRequest);11 this.wsServer=new WebSocket.Server({server: this.httpServer});12 this.wsServer.on('connection',this.onWsConnection)13 this.connectionsById={};14 this.logEnabled=false;15 this.delay=5000;16 }17 setKey(key) {18 this.key=key;19 }20 setLogEnabled(enabled) {21 this.logEnabled=enabled;22 }23 log=(message)=>{24 if (this.logEnabled)25 console.log("** rbs: "+message);26 }27 onHttpRequest=(req, res)=>{28 this.log("HTTP request: "+req.url);29 let u=url.parse(req.url);30 let path=u.pathname.split("/").filter(x=>x);31 if (this.key && req.headers["x-api-key"]!=this.key) {32 res.statusCode=403;33 res.statusMessage="Bad api key.";34 res.end("Not authorized.");35 return;36 }37 if (path.length==0) {38 let response={39 devices: Object.keys(this.connectionsById),40 restbrokerVersion: restbrokerPackage.version41 };42 res.end(JSON.stringify(response,null,2)+"\n");43 }44 else {45 if (!Object.keys(this.connectionsById).includes(path[0])) {46 res.end("Device not connected");47 return;48 }49 let id=path[0];50 path=path.slice(1);51 req.url="/"+path.join("/")+(u.search?u.search:"");52 this.connectionsById[id].handleRequest(req,res);53 }54 }55 onWsConnection=(ws, req)=>{56 this.log("WebSocket connection.");57 let connection=new ServerConnection(this, ws, req);58 if (!connection.getId()) {59 this.log("Connection doesn't have an id, closing");60 connection.close();61 return;62 }63 if (this.key && connection.getKey()!=this.key) {64 this.log("Bad api key, closing.");65 connection.close();66 return;67 }68 let id=connection.getId();69 if (this.connectionsById[id]) {70 this.connectionsById[id].off("close",this.onConnectionClose);71 this.connectionsById[id].close();72 delete this.connectionsById[id];73 }74 connection.on("close",this.onConnectionClose);75 this.connectionsById[id]=connection;76 this.emit("connectionsChange");77 }78 onConnectionClose=(connection)=>{79 this.log("WebSocket connection closed.");80 connection.off("close",this.onConnectionClose);81 delete this.connectionsById[connection.getId()];82 this.emit("connectionsChange");83 }84 listen(port) {85 this.httpServer.listen(port);86 this.log("Listening to: "+port)87 }88 close() {89 for (let id in this.connectionsById)90 this.connectionsById[id].close();91 this.httpServer.close();92 }93}...
ws.huobi.js
Source:ws.huobi.js
...48 onWsFailed(error) {49 console.log(_t.name, 'èæºé误', error.toString());50 _t.reWsConnection()51 },52 onWsConnection(connection) {53 console.log(_t.name, 'èæºæå')54 connection.on('error', _t.onConnectError);55 connection.on('close', _t.onConnectClose);56 connection.on('message', _t.onConnectMessage);57 connection.sendUTF(JSON.stringify(_t.subscribe.ticker))58 },59 reWsConnection() {60 console.log(_t.name, 'éæ°èæº');61 clearTimeout(this.tempTimeout)62 _t.tempTimeout = setTimeout(() => {63 _t.init()64 }, 1000 * 3)65 },66 async init() {...
wsconnection.js
Source:wsconnection.js
...4 this.wss = new WebSocket.Server(options.server);5 this.wss.on('connection', this.onWsConnection.bind(this));6 this.wss.on('ws:send', this.onWsSend.bind(this));7 }8 onWsConnection(ws, req) {9 // ws.id = req.sessionID;10 ws.id = req.session.userId;11 ws.tipo = req.tipo;12 ws.on('message', message => {13 this.onWsMessage.apply(this, [ws, message]);14 });15 ws.on('close', message => {16 this.onWsClose.apply(this, [ws, message]);17 });18 ws.on('error', message => {19 this.onWsError.apply(this, [this, message]);20 });21 // this.wss.emit('wss:connection:new', ws);22 }...
index.js
Source:index.js
...39 resolve(msg);40 });41 });42 }43 onWsConnection(connection) {44 this.wsConnection = connection;45 connection.sendMsg({46 type: 'meta',47 name: 'server'48 });49 }50 51}...
testWSS.js
Source:testWSS.js
1const { WSServer } = require('../configs');2const WSClient = require('../src').WSClient;3class Batman {4 constructor(configs) {5 this.configs = configs;6 this.connectToWSS();7 }8 onCharacteristicReceive(characteristic) {9 this.bleService = characteristic;10 this.connectToWSS();11 }12 readSensorData(cb) {13 setTimeout(() => {14 cb({ 15 date: new Date(),16 type: 'text',17 data: { temperature: '28.0*C', humidity: '20.0%' },18 rssi: -79 19 });20 }, 200);21 }22 handleWSSMsg(message) {23 switch (message.type) {24 case 'request':25 if (message.data === 'get_dht_sensor_data') {26 this.readSensorData((data) => {27 console.log(data);28 this.wssConnection.sendMsg({29 type: 'response',30 data: data31 })32 });33 }34 }35 }36 onWSConnection(connection) {37 this.wssConnection = connection;38 connection.onMsg(message => {39 this.handleWSSMsg(message)40 });41 }42 connectToWSS() {43 const { WSServer } = this.configs;44 const wsClient = new WSClient({45 port: WSServer.port,46 serverLink: WSServer.ip,47 onConnection: this.onWSConnection.bind(this)48 });49 }50}51new Batman({52 WSServer...
whiteboard.js
Source:whiteboard.js
...8const wsServer = new WebSocket.Server({9 server10})11wsServer.on('connection', onWsConnection)12function onWsConnection(socket) {13 const client = new Client({14 server: wsServer,15 socket16 })17 socket.on('message', client.onWsMessage)18}19class Client {20 server = null21 socket = null22 constructor(props) {23 Object.assign(this, props)24 }25 onWsMessage = (message) => {26 this.server.clients.forEach(client => {...
Using AI Code Generation
1const ws = require('ws');2const wss = new ws.Server({ port: 8080 });3wss.on('connection', function connection(ws) {4 ws.on('message', function incoming(message) {5 console.log('received: %s', message);6 });7 ws.send('something');8});9const WebSocket = require('ws');10ws.on('open', function open() {11 ws.send('something');12});13ws.on('message', function incoming(data) {14 console.log(data);15});16const WebSocket = require('ws');17ws.on('open', function open() {18 ws.send('something');19});20ws.on('close', function close() {21 console.log('disconnected');22});
Using AI Code Generation
1const WebSocket = require('ws');2ws.on('open', function open() {3 ws.send('something');4});5ws.on('message', function incoming(data) {6 console.log(data);7});8describe('Test', () => {9 it('Test', () => {10 ws.on('message', (data) => {11 console.log(data);12 });13 });14 });15});16 ws.on('message', (data) => {17 console.log(data);18 });19 ws.send('something');20});21 ws.on('message', (data) => {22 console.log(data);23 });24 ws.send('something');25});26 ws.on('message', (data) => {27 console.log(data);28 });29 ws.send('something');30});31 ws.on('message', (data) => {32 console.log(data);33 });34 ws.send('
Using AI Code Generation
1Cypress.on('window:before:load', (win) => {2 win.WebSocket = class extends WebSocket {3 constructor(url, protocols) {4 super(url, protocols)5 this.addEventListener('open', () => {6 this.send('Hello from the client!')7 })8 }9 }10})11Cypress.on('window:before:load', (win) => {12 win.WebSocket = class extends WebSocket {13 constructor(url, protocols) {14 super(url, protocols)15 this.addEventListener('message', (event) => {16 console.log('Message from the server:', event.data)17 })18 }19 }20})21Cypress.on('window:before:load', (win) => {22 win.WebSocket = class extends WebSocket {23 constructor(url, protocols) {24 super(url, protocols)25 this.addEventListener('close', (event) => {26 console.log('Server closed the connection:', event.code, event.reason)27 })28 }29 }30})31Cypress.on('window:before:load', (win) => {32 win.WebSocket = class extends WebSocket {33 constructor(url, protocols) {34 super(url, protocols)35 this.addEventListener('error', (event) => {36 console.log('Server closed the connection:', event.code, event.reason)37 })38 }39 }40})41Cypress.on('window:before:load', (win) => {42 win.WebSocket = class extends WebSocket {43 constructor(url, protocols) {44 super(url, protocols)45 this.addEventListener('open', () => {46 console.log('Connection established!')47 })48 }49 }50})51Cypress.on('window:before:load', (win) => {52 win.WebSocket = class extends WebSocket {53 constructor(url, protocols) {54 super(url, protocols)55 this.addEventListener('message', (event) => {56 console.log('Message from the server:', event.data)57 })58 }59 }60})61Cypress.on('window:before:load', (win) => {62 win.WebSocket = class extends WebSocket {63 constructor(url, protocols) {64 super(url, protocols)65 this.addEventListener('close', (
Using AI Code Generation
1onWsConnection (cb) {2 this.wsConnectionCallbacks.push(cb)3 }4onWsMessage (cb) {5 this.wsMessageCallbacks.push(cb)6 }7onWsClose (cb) {8 this.wsCloseCallbacks.push(cb)9 }10onWsError (cb) {11 this.wsErrorCallbacks.push(cb)12 }13Cypress.onWsConnection = (cb) => {14 cy.task('onWsConnection', cb)15 }16Cypress.onWsMessage = (cb) => {17 cy.task('onWsMessage', cb)18 }19Cypress.onWsClose = (cb) => {20 cy.task('onWsClose', cb)21 }22Cypress.onWsError = (cb) => {23 cy.task('onWsError', cb)24 }25Cypress.Commands.add('onWsConnection', (cb) => {26 Cypress.onWsConnection(cb)27 })28Cypress.Commands.add('onWsMessage', (cb) => {29 Cypress.onWsMessage(cb)30 })31Cypress.Commands.add('onWsClose', (cb) => {32 Cypress.onWsClose(cb)33 })34Cypress.Commands.add('onWsError', (cb) => {35 Cypress.onWsError(cb)36 })37on('task', {38 onWsConnection (cb) {39 return Cypress.backend('onWsConnection', cb)40 }41 })42on('task', {43 onWsMessage (cb) {44 return Cypress.backend('onWsMessage', cb)45 }46 })
Using AI Code Generation
1Cypress.on("window:before:load", (win) => {2 cy.stub(win.console, "log").as("consoleLog");3});4Cypress.Commands.add("onWsConnection", (url, cb) => {5 cy.window().then((win) => {6 const ws = new win.WebSocket(url);7 ws.onopen = () => {8 cb(ws);9 };10 });11});12Cypress.Commands.add("onWsMessage", (ws, cb) => {13 ws.onmessage = (event) => {14 const data = JSON.parse(event.data);15 cb(data);16 };17});18Cypress.Commands.add("onWsClose", (ws, cb) => {19 ws.onclose = () => {20 cb();21 };22});23Cypress.Commands.add("onWsError", (ws, cb) => {24 ws.onerror = (event) => {25 const error = event.message;26 cb(error);27 };28});29Cypress.Commands.add("sendWsMessage", (ws, message) => {30 const data = JSON.stringify(message);31 ws.send(data);32});33import "./commands";34describe("Test", () => {35 it("should test", () => {36 cy.onWsMessage(ws, (data) => {37 cy.log(data);38 });39 cy.onWsError(ws, (error) => {40 cy.log(error);41 });42 cy.onWsClose(ws, () => {43 cy.log("Connection closed");44 });45 cy.sendWsMessage(ws, { hello: "world" });46 });47 });48});
Using AI Code Generation
1Cypress.on('window:before:load', (win) => {2 win.onWsConnection = (callback) => {3 ws.onopen = () => {4 callback(ws);5 };6 };7});8describe('test websocket', () => {9 it('should send message to websocket server', () => {10 cy.visit('index.html');11 cy.window().then((win) => {12 win.onWsConnection((ws) => {13 ws.send('Hello World!');14 });15 });16 });17});18module.exports = (on, config) => {19 on('task', {20 connectToWsServer: (url) => {21 const WebSocket = require('ws');22 const ws = new WebSocket(url);23 return new Promise((resolve) => {24 ws.onopen = () => {25 resolve(ws);26 };27 });28 },29 });30};31describe('test websocket', () => {32 it('should send message to websocket server', () => {33 cy.visit('index.html');34 cy.window().then((win) => {35 (ws) => {36 ws.send('Hello World!');37 }38 );39 });40 });41});
Using AI Code Generation
1const WebSocket = require('ws');2ws.on('open', function open() {3 ws.send('something');4});5ws.on('message', function incoming(data) {6 console.log(data);7});8ws.on('close', function close() {9 console.log('disconnected');10});11describe('WebSocket', () => {12 it('should receive message', () => {13 cy.onWsMessage().then((data) => {14 console.log(data);15 });16 });17});18const WebSocket = require('ws');19module.exports = (on, config) => {20 on('task', {21 connectToWebsocketServer() {22 ws.on('open', function open() {23 ws.send('something');24 });25 ws.on('message', function incoming(data) {26 console.log(data);27 });28 ws.on('close', function close() {29 console.log('disconnected');30 });31 return null;32 },33 });34};35Cypress.Commands.add('onWsConnection', () => {36 cy.task('connectToWebsocketServer');37});38const WebSocket = require('ws');39Cypress.on('window:before:load', (win) => {40 win.WebSocket = WebSocket;41});42Cypress.on('window:load', (win) => {43 win.addEventListener('message', (event) => {44 if (event.data.type === 'websocket:message') {45 console.log(event.data);46 }47 });48});49Cypress.Commands.add('onWsMessage', () => {50 cy.window().then((win) => {51 return new Cypress.Promise((resolve) => {
Using AI Code Generation
1Cypress.on("window:before:load", (win) => {2 cy.on("window:load", (win) => {3 win.onWsConnection((ws) => {4 ws.send("hello");5 });6 });7});8Cypress.on("window:before:load", (win) => {9 win.onWsConnection((ws) => {10 ws.send("hello");11 });12});13Cypress.on("window:before:load", (win) => {14 win.onWsConnection = (onConnection) => {15 const originalWebSocket = win.WebSocket;16 win.WebSocket = function (url, protocols) {17 const ws = new originalWebSocket(url, protocols);18 onConnection(ws);19 return ws;20 };21 };22});23Cypress.on("window:before:load", (win) => {24 win.onWsConnection = (onConnection) => {25 const originalWebSocket = win.WebSocket;26 win.WebSocket = function (url, protocols) {27 const ws = new originalWebSocket(url, protocols);28 onConnection(ws);29 return ws;30 };31 };32});33Cypress.on("window:before:load", (win) => {34 win.onWsConnection = (onConnection) => {35 const originalWebSocket = win.WebSocket;36 win.WebSocket = function (url, protocols) {37 const ws = new originalWebSocket(url, protocols);38 onConnection(ws);39 return ws;40 };41 };42});43Cypress.on("window:before:load", (win) => {44 win.onWsConnection = (onConnection) => {45 const originalWebSocket = win.WebSocket;46 win.WebSocket = function (url, protocols) {47 const ws = new originalWebSocket(url, protocols);48 onConnection(ws);49 return ws;50 };51 };52});53Cypress.on("window:before:load", (win) => {54 win.onWsConnection = (onConnection) => {55 const originalWebSocket = win.WebSocket;56 win.WebSocket = function (url, protocols) {57 const ws = new originalWebSocket(url, protocols);58 onConnection(ws);59 return ws;60 };61 };62});
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!