How to use CreateWebSocket method in wpt

Best JavaScript code snippet using wpt

websocket-spec.js

Source:websocket-spec.js Github

copy

Full Screen

1/*2 * Copyright 2015-present Open Networking Laboratory3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/*17 ONOS GUI -- Remote -- Web Socket Service - Unit Tests18 */19describe('factory: fw/remote/websocket.js', function () {20 var $log, fs, wss;21 var noop = function () {},22 send = jasmine.createSpy('send').and.callFake(function (ev) {23 return ev;24 }),25 mockWebSocket = {26 send: send27 };28 beforeEach(module('onosRemote', 'onosLayer', 'ngRoute', 'onosNav', 'onosSvg'));29 beforeEach(function () {30 mockWebSocket = {31 send: send32 };33 });34 beforeEach(function () {35 module(function ($provide) {36 $provide.factory('WSock', function () {37 return {38 newWebSocket: function () {39 return mockWebSocket;40 }41 };42 });43 });44 });45 beforeEach(module(function($provide) {46 $provide.factory('$location', function () {47 return {48 protocol: function () { return 'http'; },49 host: function () { return 'foo'; },50 port: function () { return '80'; },51 search: function() {52 return {debug: 'true'};53 }54 };55 })56 }));57 beforeEach(inject(function (_$log_, FnService, WebSocketService) {58 $log = _$log_;59 fs = FnService;60 wss = WebSocketService;61 wss.resetState();62 }));63 it('should define WebSocketService', function () {64 expect(wss).toBeDefined();65 });66 it('should define api functions', function () {67 expect(fs.areFunctions(wss, [68 'resetSid', 'resetState',69 'createWebSocket', 'bindHandlers', 'unbindHandlers',70 'addOpenListener', 'removeOpenListener', 'sendEvent',71 'isConnected', 'loggedInUser',72 '_setVeilDelegate', '_setLoadingDelegate'73 ])).toBeTruthy();74 });75 it('should use the appropriate URL, createWebsocket', function () {76 var url = wss.createWebSocket();77 expect(url).toEqual('ws://foo:80/onos/ui/websock/core');78 });79 it('should use the appropriate URL with modified port, createWebsocket',80 function () {81 var url = wss.createWebSocket({ wsport: 1243 });82 expect(url).toEqual('ws://foo:1243/onos/ui/websock/core');83 });84 it('should verify websocket event handlers, createWebsocket', function () {85 wss.createWebSocket({ wsport: 1234 });86 expect(fs.isF(mockWebSocket.onopen)).toBeTruthy();87 expect(fs.isF(mockWebSocket.onmessage)).toBeTruthy();88 expect(fs.isF(mockWebSocket.onclose)).toBeTruthy();89 });90 it('should invoke listener callbacks when websocket is up, handleOpen',91 function () {92 var num = 0;93 function incrementNum() { num++; }94 wss.addOpenListener(incrementNum);95 wss.createWebSocket({ wsport: 1234 });96 mockWebSocket.onopen();97 expect(num).toBe(1);98 });99 it('should send pending events, handleOpen', function () {100 var fakeEvent = {101 event: 'mockEv',102 sid: 1,103 payload: { mock: 'thing' }104 };105 wss.sendEvent(fakeEvent.event, fakeEvent.payload);106 expect(mockWebSocket.send).not.toHaveBeenCalled();107 wss.createWebSocket({ wsport: 1234 });108 mockWebSocket.onopen();109 expect(mockWebSocket.send).toHaveBeenCalledWith(JSON.stringify(fakeEvent));110 });111 it('should handle an incoming bad JSON message, handleMessage', function () {112 spyOn($log, 'error');113 var badMsg = {114 data: 'bad message'115 };116 wss.createWebSocket({ wsport: 1234 });117 expect(mockWebSocket.onmessage(badMsg)).toBeNull();118 expect($log.error).toHaveBeenCalled();119 });120 it('should verify message was handled, handleMessage', function () {121 var num = 0,122 fakeHandler = {123 mockEvResp: function () { num++; }124 },125 data = JSON.stringify({126 event: 'mockEvResp',127 payload: {}128 }),129 event = {130 data: data131 };132 wss.createWebSocket({ wsport: 1234 });133 wss.bindHandlers(fakeHandler);134 expect(mockWebSocket.onmessage(event)).toBe(undefined);135 expect(num).toBe(1);136 });137 it('should warn if there is an unhandled event, handleMessage', function () {138 spyOn($log, 'warn');139 var data = { foo: 'bar', bar: 'baz'},140 dataString = JSON.stringify(data),141 badEv = {142 data: dataString143 };144 wss.createWebSocket({ wsport: 1234 });145 mockWebSocket.onmessage(badEv);146 expect($log.warn).toHaveBeenCalledWith('Unhandled event:', data);147 });148 it('should not warn if valid input, bindHandlers', function () {149 spyOn($log, 'warn');150 expect(wss.bindHandlers({151 foo: noop,152 bar: noop153 })).toBe(undefined);154 expect($log.warn).not.toHaveBeenCalled();155 });156 it('should warn if no arguments, bindHandlers', function () {157 spyOn($log, 'warn');158 expect(wss.bindHandlers()).toBeNull();159 expect($log.warn).toHaveBeenCalledWith(160 'WSS.bindHandlers(): no event handlers'161 );162 expect(wss.bindHandlers({})).toBeNull();163 expect($log.warn).toHaveBeenCalledWith(164 'WSS.bindHandlers(): no event handlers'165 );166 });167 it('should warn if handler is not a function, bindHandlers', function () {168 spyOn($log, 'warn');169 expect(wss.bindHandlers({170 foo: 'handler1',171 bar: 3,172 baz: noop173 })).toBe(undefined);174 expect($log.warn).toHaveBeenCalledWith('foo handler not a function');175 expect($log.warn).toHaveBeenCalledWith('bar handler not a function');176 });177 it('should warn if duplicate handlers were given, bindHandlers',178 function () {179 spyOn($log, 'warn');180 wss.bindHandlers({181 foo: noop182 });183 expect(wss.bindHandlers({184 foo: noop185 })).toBe(undefined);186 expect($log.warn).toHaveBeenCalledWith('duplicate bindings ignored:',187 ['foo']);188 });189 it('should warn if no arguments, unbindHandlers', function () {190 spyOn($log, 'warn');191 expect(wss.unbindHandlers()).toBeNull();192 expect($log.warn).toHaveBeenCalledWith(193 'WSS.unbindHandlers(): no event handlers'194 );195 expect(wss.unbindHandlers({})).toBeNull();196 expect($log.warn).toHaveBeenCalledWith(197 'WSS.unbindHandlers(): no event handlers'198 );199 });200 // Note: cannot test unbindHandlers' forEach due to it using closure variable201 it('should not warn if valid argument, addOpenListener', function () {202 spyOn($log, 'warn');203 var o = wss.addOpenListener(noop);204 expect(o.id === 1);205 expect(o.cb === noop);206 expect($log.warn).not.toHaveBeenCalled();207 o = wss.addOpenListener(noop);208 expect(o.id === 2);209 expect(o.cb === noop);210 expect($log.warn).not.toHaveBeenCalled();211 });212 it('should log error if callback not a function, addOpenListener',213 function () {214 spyOn($log, 'error');215 var o = wss.addOpenListener('foo');216 expect(o.id === 1);217 expect(o.cb === 'foo');218 expect(o.error === 'No callback defined');219 expect($log.error).toHaveBeenCalledWith(220 'WSS.addOpenListener(): callback not a function'221 );222 });223 it('should not warn if valid listener object, removeOpenListener', function () {224 spyOn($log, 'warn');225 expect(wss.removeOpenListener({226 id: 1,227 cb: noop228 })).toBe(undefined);229 expect($log.warn).not.toHaveBeenCalled();230 });231 it('should warn if listener is invalid, removeOpenListener', function () {232 spyOn($log, 'warn');233 expect(wss.removeOpenListener({})).toBeNull();234 expect($log.warn).toHaveBeenCalledWith(235 'WSS.removeOpenListener(): invalid listener', {}236 );237 expect(wss.removeOpenListener('listener')).toBeNull();238 expect($log.warn).toHaveBeenCalledWith(239 'WSS.removeOpenListener(): invalid listener', 'listener'240 );241 });242 // Note: handleClose is not currently tested due to all work it does relies243 // on closure variables that cannot be mocked...

Full Screen

Full Screen

mqtt.test.jsx

Source:mqtt.test.jsx Github

copy

Full Screen

1import { h } from 'preact';2import { Mqtt, MqttProvider, useMqtt } from '../mqtt';3import { useCallback, useContext } from 'preact/hooks';4import { fireEvent, render, screen } from '@testing-library/preact';5function Test() {6 const { state } = useContext(Mqtt);7 return state.__connected ? (8 <div data-testid="data">9 {Object.keys(state).map((key) => (10 <div data-testid={key}>{JSON.stringify(state[key])}</div>11 ))}12 </div>13 ) : null;14}15const TEST_URL = 'ws://test-foo:1234/ws';16describe('MqttProvider', () => {17 let createWebsocket, wsClient;18 beforeEach(() => {19 wsClient = {20 close: jest.fn(),21 send: jest.fn(),22 };23 createWebsocket = jest.fn((url) => {24 wsClient.args = [url];25 return new Proxy(26 {},27 {28 get(target, prop, receiver) {29 return wsClient[prop];30 },31 set(target, prop, value) {32 wsClient[prop] = typeof value === 'function' ? jest.fn(value) : value;33 if (prop === 'onopen') {34 wsClient[prop]();35 }36 return true;37 },38 }39 );40 });41 });42 test('connects to the mqtt server', async () => {43 render(44 <MqttProvider config={mockConfig} createWebsocket={createWebsocket} mqttUrl={TEST_URL}>45 <Test />46 </MqttProvider>47 );48 await screen.findByTestId('data');49 expect(wsClient.args).toEqual([TEST_URL]);50 expect(screen.getByTestId('__connected')).toHaveTextContent('true');51 });52 test('receives data through useMqtt', async () => {53 function Test() {54 const {55 value: { payload, retain },56 connected,57 } = useMqtt('tacos');58 return connected ? (59 <div>60 <div data-testid="payload">{JSON.stringify(payload)}</div>61 <div data-testid="retain">{JSON.stringify(retain)}</div>62 </div>63 ) : null;64 }65 const { rerender } = render(66 <MqttProvider config={mockConfig} createWebsocket={createWebsocket} mqttUrl={TEST_URL}>67 <Test />68 </MqttProvider>69 );70 await screen.findByTestId('payload');71 wsClient.onmessage({72 data: JSON.stringify({ topic: 'tacos', payload: JSON.stringify({ yes: true }), retain: false }),73 });74 rerender(75 <MqttProvider config={mockConfig} createWebsocket={createWebsocket} mqttUrl={TEST_URL}>76 <Test />77 </MqttProvider>78 );79 expect(screen.getByTestId('payload')).toHaveTextContent('{"yes":true}');80 expect(screen.getByTestId('retain')).toHaveTextContent('false');81 });82 test('can send values through useMqtt', async () => {83 function Test() {84 const { send, connected } = useMqtt('tacos');85 const handleClick = useCallback(() => {86 send({ yes: true });87 }, [send]);88 return connected ? <button onClick={handleClick}>click me</button> : null;89 }90 render(91 <MqttProvider config={mockConfig} createWebsocket={createWebsocket} mqttUrl={TEST_URL}>92 <Test />93 </MqttProvider>94 );95 await screen.findByRole('button');96 fireEvent.click(screen.getByRole('button'));97 await expect(wsClient.send).toHaveBeenCalledWith(98 JSON.stringify({ topic: 'tacos', payload: JSON.stringify({ yes: true }) })99 );100 });101 test('prefills the recordings/detect/snapshots state from config', async () => {102 jest.spyOn(Date, 'now').mockReturnValue(123456);103 const config = {104 cameras: {105 front: { name: 'front', detect: { enabled: true }, record: { enabled: false }, snapshots: { enabled: true } },106 side: { name: 'side', detect: { enabled: false }, record: { enabled: false }, snapshots: { enabled: false } },107 },108 };109 render(110 <MqttProvider config={config} createWebsocket={createWebsocket} mqttUrl={TEST_URL}>111 <Test />112 </MqttProvider>113 );114 await screen.findByTestId('data');115 expect(screen.getByTestId('front/detect/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"ON"}');116 expect(screen.getByTestId('front/recordings/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"OFF"}');117 expect(screen.getByTestId('front/snapshots/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"ON"}');118 expect(screen.getByTestId('side/detect/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"OFF"}');119 expect(screen.getByTestId('side/recordings/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"OFF"}');120 expect(screen.getByTestId('side/snapshots/state')).toHaveTextContent('{"lastUpdate":123456,"payload":"OFF"}');121 });122});123const mockConfig = {124 cameras: {},...

Full Screen

Full Screen

websocket.js

Source:websocket.js Github

copy

Full Screen

1function createWebSocket(obj){2 if(!window.WebSocket) return {content:'您的浏览器不支持WebSocket'}3 this.ws = null;4 this.heartCheck = {5 url:obj.url,//websocket的地址6 firstTimeOut:obj.firstTimeOut,//第一次请求websocket时间7 timeout:obj.timeout, //心跳间隔时间,8 delayTimeOut:obj.delayTimeOut,//出现异常或报错后重新链接时的间隔时间9 timeoutObj:null,//每次心跳请求的定时器10 serverTimeoutObj: null,//每次心跳后没收到后台信息隔断时间关闭websocket的定时器11 }12 // this.onclose = function() {};13 // this.onerror = function() {};14 // this.onopen = function() {};15 // this.onmessage = function() {};16 // this.onreconnect = function() {};17 this.init();18};19createWebSocket.prototype.init = function() {20 try {21 this.ws = new WebSocket(this.heartCheck.url);22 this.initConnect();23 } catch(e) {24 console.log('catch');25 this.reconnect();26 }27};28createWebSocket.prototype.initConnect = function() {29 this.ws.onopen = function(event) {30 this.onopen(event);31 this.start(this.heartCheck.firstTimeOut);32 }.bind(this);33 this.ws.onmessage = function(event) {34 this.onmessage(event);35 this.reset();36 }.bind(this)37 this.ws.onclose = function(event) {38 console.log('关闭');39 this.onclose(event);40 this.reconnect();41 }.bind(this);42 this.ws.onerror = function(err) {43 this.onerror(event);44 this.reconnect();45 }.bind(this);46};47createWebSocket.prototype.reconnect = function() {48 //this.lockReconnect节流,出现异常没连接上会一直重连,设置延迟避免请求过多49 //this.handleCloseReconnect前端手工关闭50 if (this.lockReconnect || this.handleCloseReconnect) return;51 this.lockReconnect = true;52 this.tt && clearTimeout(this.tt);53 this.tt = setTimeout(function() {54 this.init();55 this.lockReconnect = false;56 }.bind(this), this.heartCheck.delayTimeOut);57};58createWebSocket.prototype.reset = function() {59 //当心跳后onmessage无法接收后台返回数据,无法reset则无法清除定时器this.serverTimeoutObj,60 //一段时间后定时器this.serverTimeoutObj关闭websocket触发onclose,重新reconnect61 clearTimeout(this.timeoutObj);62 clearTimeout(this.serverTimeoutObj);63 this.start(this.heartCheck.timeout);64};65createWebSocket.prototype.start = function(time) {66 this.timeoutObj = setTimeout(function() {67 this.ws.send(JSON.stringify({68 "ping": 1821255800069 }));70 this.serverTimeoutObj = setTimeout(function() {71 this.ws.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次72 }.bind(this), this.heartCheck.delayTimeOut)73 }.bind(this), time)74};75createWebSocket.prototype.close = function () {76 //如果手动关闭连接,不再重连77 this.ws.close();78 this.handleCloseReconnect = true;79 clearTimeout(this.timeoutObj);80 clearTimeout(this.serverTimeoutObj);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptool = require('wptool');2ws.on('open', function open() {3 console.log('connected');4 ws.send('something');5});6ws.on('message', function(data, flags) {7 console.log('received: %s', data);8});9ws.on('close', function() {10 console.log('disconnected');11});12ws.on('error', function() {13 console.log('error');14});15var wptool = require('wptool');16ws.on('open', function open() {17 console.log('connected');18 ws.send('something');19});20ws.on('message', function(data, flags) {21 console.log('received: %s', data);22});23ws.on('close', function() {24 console.log('disconnected');25});26ws.on('error', function() {27 console.log('error');28});29var wptool = require('wptool');30ws.on('open', function open() {31 console.log('connected');32 ws.send('something');33});34ws.on('message', function(data, flags) {35 console.log('received: %s', data);36});37ws.on('close', function() {38 console.log('disconnected');39});40ws.on('error', function() {41 console.log('error');42});43var wptool = require('wptool');44ws.on('open', function open() {45 console.log('connected');46 ws.send('something');47});48ws.on('message', function(data, flags) {49 console.log('received: %s', data);50});51ws.on('close', function() {52 console.log('disconnected');53});54ws.on('error', function() {55 console.log('error');56});57var wptool = require('wptool');

Full Screen

Using AI Code Generation

copy

Full Screen

1ws.onopen = function() {2 ws.send("Hello, world");3};4ws.onmessage = function (evt) {5 var received_msg = evt.data;6 console.log("Message is received...");7};8ws.onclose = function() {9 console.log("Connection is closed...");10};11var wptb = (function () {12 var wptb = {};13 wptb.CreateWebSocket = function (url) {14 return new WebSocket(url);15 };16 return wptb;17})();18ws.onopen = function() {19 ws.send("Hello, world");20};21ws.onmessage = function (evt) {22 var received_msg = evt.data;23 console.log("Message is received...");24};25ws.onclose = function() {26 console.log("Connection is closed...");27};28var wptb = (function () {29 var wptb = {};30 wptb.CreateWebSocket = function (url) {31 return new WebSocket(url);32 };33 return wptb;34})();

Full Screen

Using AI Code Generation

copy

Full Screen

1ws.onopen = function() { alert("opened"); };2ws.onmessage = function(evt) { alert(evt.data); };3ws.onclose = function() { alert("closed"); };4ws.onerror = function() { alert("error"); };5ws.send("Hello World!");6Websocket Testbed (2)7Websocket Testbed (3)8Websocket Testbed (4)

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptb = require('wptb');2ws.onopen = function() {3 console.log('Connected');4 ws.send('Hello, world');5};6ws.onmessage = function(e) {7 console.log('Server: ' + e.data);8};9ws.onclose = function() {10 console.log('Disconnected');11};12var wptb = require('wptb');13ws.onopen = function() {14 console.log('Connected');15 ws.send('Hello, world');16};17ws.onmessage = function(e) {18 console.log('Server: ' + e.data);19};20ws.onclose = function() {21 console.log('Disconnected');22};23var wptb = require('wptb');24ws.onopen = function() {25 console.log('Connected');26 ws.send('Hello, world');27};28ws.onmessage = function(e) {29 console.log('Server: ' + e.data);30};31ws.onclose = function() {32 console.log('Disconnected');33};

Full Screen

Using AI Code Generation

copy

Full Screen

1ws.onmessage = function (evt) { 2 var received_msg = evt.data;3 console.log("Message is received...");4};5ws.onclose = function() { 6 console.log("Connection is closed..."); 7};8var WebSocketServer = require('ws').Server9 , wss = new WebSocketServer({port: 8080});10wss.on('connection', function(ws) {11 ws.on('message', function(message) {12 console.log('received: %s', message);13 });14 ws.send('something');15});

Full Screen

Using AI Code Generation

copy

Full Screen

1public class Test {2public static void main(String[] args) throws InterruptedException {3 WebDriver driver = new FirefoxDriver();4 driver.findElement(By.id("gbqfq")).sendKeys("Selenium");5 driver.findElement(By.id("gbqfb")).click();6 Thread.sleep(5000);7 driver.quit();8}9}10 at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:192)11 at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:144)12 at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:554)13 at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions.addCookie(RemoteWebDriver.java:603)14 at org.openqa.selenium.remote.server.handler.AddCookie.call(AddCookie.java:45)15 at org.openqa.selenium.remote.server.handler.AddCookie.call(AddCookie.java:1)16 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)17 at java.util.concurrent.FutureTask.run(FutureTask.java:138)

Full Screen

Using AI Code Generation

copy

Full Screen

1ws.onmessage = function (evt) {2 console.log("Message received: " + evt.data);3};4ws.onopen = function () {5 console.log("WebSocket opened");6 ws.send("Hello, world");7};8ws.onclose = function () {9 console.log("WebSocket closed");10};11ws.onerror = function (evt) {12 console.log("WebSocket error: " + evt.data);13};14var CreateWebSocket = function (url, protocol) {15 var ws = new WebSocket(url, protocol);16 return ws;17};

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require("wpt.js");2ws.onmessage = function (evt) {3 console.log(evt.data);4}5ws.send("hello");6function CreateWebSocket(url) {7 var ws = new WebSocket(url);8 ws.onopen = function (evt) {9 console.log("Websocket connection established");10 }11 ws.onclose = function (evt) {12 console.log("Websocket connection closed");13 }14 return ws;15}16exports.CreateWebSocket = CreateWebSocket;17var request = require("request");18 console.log("error:" + error);19 console.log("response:" + response);20 console.log("body:" + body);21});22function CreateWebSocket(url) {23 var ws = new WebSocket(url);24 ws.onopen = function (evt) {25 console.log("Websocket connection established");26 }27 ws.onclose = function (evt) {28 console.log("Websocket connection closed");29 }30 return ws;31}32exports.CreateWebSocket = CreateWebSocket;33var wpt = require("wpt.js");

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptools = require('wptools');2var wp = new wptools();3wp.CreateWebSocket();4var WebSocket = require('ws');5function CreateWebSocket() {6 ws.on('open', function open() {7 console.log('connected');8 });9 ws.on('message', function(data, flags) {10 console.log(data);11 });12 ws.on('close', function() {13 console.log('disconnected');14 });15 ws.on('error', function() {16 console.log('error');17 });18}19module.exports = CreateWebSocket;

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful