How to use MockSocket method in Karma

Best JavaScript code snippet using karma

proxyconnection.js

Source:proxyconnection.js Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * You may obtain a copy of the License at5 *6 * http://www.apache.org/licenses/LICENSE-2.07 *8 * Unless required by applicable law or agreed to in writing, software9 * distributed under the License is distributed on an "AS IS" BASIS,10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11 * See the License for the specific language governing permissions and12 * limitations under the License.13 */14'use strict';15const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition;16const ConnectionManager = require('composer-common').ConnectionManager;17const ProxyConnection = require('../lib/proxyconnection');18const ProxySecurityContext = require('../lib/proxysecuritycontext');19const serializerr = require('serializerr');20const chai = require('chai');21chai.should();22chai.use(require('chai-as-promised'));23const sinon = require('sinon');24describe('ProxyConnection', () => {25 const connectionProfile = 'defaultProfile';26 const businessNetworkIdentifier = 'org-acme-biznet';27 const connectionID = '3d382385-47a5-4be9-99b0-6b10166b9497';28 const enrollmentID = 'alice1';this;29 const enrollmentSecret = 'suchs3cret';30 const securityContextID = '9d05d73e-81bf-4d8a-a874-4b561670432e';31 const serializedError = serializerr(new TypeError('such type error'));32 let mockConnectionManager;33 let mockSocket;34 let connection;35 let mockSecurityContext;36 beforeEach(() => {37 mockConnectionManager = sinon.createStubInstance(ConnectionManager);38 mockSocket = {39 emit: sinon.stub(),40 removeListener: sinon.stub()41 };42 mockSocket.emit.throws(new Error('unexpected call'));43 connection = new ProxyConnection(mockConnectionManager, connectionProfile, businessNetworkIdentifier, mockSocket, connectionID);44 mockSecurityContext = new ProxySecurityContext(connection, enrollmentID, securityContextID);45 });46 describe('#disconnect', () => {47 it('should send a disconnect call to the connector server', () => {48 mockSocket.emit.withArgs('/api/connectionDisconnect', connectionID, sinon.match.func).yields(null);49 return connection.disconnect()50 .then(() => {51 sinon.assert.calledOnce(mockSocket.emit);52 sinon.assert.calledWith(mockSocket.emit, '/api/connectionDisconnect', connectionID, sinon.match.func);53 mockSocket.removeListener.withArgs('events', sinon.match.func).yield();54 });55 });56 it('should handle an error from the connector server', () => {57 mockSocket.emit.withArgs('/api/connectionDisconnect', connectionID, sinon.match.func).yields(serializedError);58 return connection.disconnect()59 .should.be.rejectedWith(TypeError, /such type error/);60 });61 });62 describe('#login', () => {63 it('should send a login call to the connector server', () => {64 mockSocket.emit.withArgs('/api/connectionLogin', connectionID, enrollmentID, enrollmentSecret, sinon.match.func).yields(null, securityContextID);65 return connection.login(enrollmentID, enrollmentSecret)66 .then((securityContext) => {67 sinon.assert.calledOnce(mockSocket.emit);68 sinon.assert.calledWith(mockSocket.emit, '/api/connectionLogin', connectionID, enrollmentID, enrollmentSecret, sinon.match.func);69 securityContext.should.be.an.instanceOf(ProxySecurityContext);70 securityContext.getUser().should.equal(enrollmentID);71 securityContext.getSecurityContextID().should.equal(securityContextID);72 });73 });74 it('should handle an error from the connector server', () => {75 mockSocket.emit.withArgs('/api/connectionLogin', connectionID, enrollmentID, enrollmentSecret, sinon.match.func).yields(serializedError);76 return connection.login(enrollmentID, enrollmentSecret)77 .should.be.rejectedWith(TypeError, /such type error/);78 });79 });80 describe('#install', () => {81 it('should send a install call to the connector server', () => {82 mockSocket.emit.withArgs('/api/connectionInstall', connectionID, securityContextID, 'org-acme-biznet', undefined, sinon.match.func).yields(null);83 return connection.install(mockSecurityContext, businessNetworkIdentifier)84 .then(() => {85 sinon.assert.calledOnce(mockSocket.emit);86 sinon.assert.calledWith(mockSocket.emit, '/api/connectionInstall', connectionID, securityContextID, 'org-acme-biznet', undefined, sinon.match.func);87 });88 });89 it('should handle an error from the connector server', () => {90 mockSocket.emit.withArgs('/api/connectionInstall', connectionID, securityContextID, 'org-acme-biznet', undefined, sinon.match.func).yields(serializedError);91 return connection.install(mockSecurityContext, businessNetworkIdentifier)92 .should.be.rejectedWith(TypeError, /such type error/);93 });94 });95 describe('#start', () => {96 let mockBusinessNetworkDefinition;97 beforeEach(() => {98 mockBusinessNetworkDefinition = sinon.createStubInstance(BusinessNetworkDefinition);99 mockBusinessNetworkDefinition.toArchive.resolves(Buffer.from('hello world'));100 });101 it('should send a start call to the connector server', () => {102 mockSocket.emit.withArgs('/api/connectionStart', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func).yields(null);103 return connection.start(mockSecurityContext, mockBusinessNetworkDefinition)104 .then(() => {105 sinon.assert.calledOnce(mockSocket.emit);106 sinon.assert.calledWith(mockSocket.emit, '/api/connectionStart', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func);107 });108 });109 it('should handle an error from the connector server', () => {110 mockSocket.emit.withArgs('/api/connectionStart', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func).yields(serializedError);111 return connection.start(mockSecurityContext, mockBusinessNetworkDefinition)112 .should.be.rejectedWith(TypeError, /such type error/);113 });114 });115 describe('#deploy', () => {116 let mockBusinessNetworkDefinition;117 beforeEach(() => {118 mockBusinessNetworkDefinition = sinon.createStubInstance(BusinessNetworkDefinition);119 mockBusinessNetworkDefinition.toArchive.resolves(Buffer.from('hello world'));120 });121 it('should send a deploy call to the connector server', () => {122 mockSocket.emit.withArgs('/api/connectionDeploy', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func).yields(null);123 return connection.deploy(mockSecurityContext, mockBusinessNetworkDefinition)124 .then(() => {125 sinon.assert.calledOnce(mockSocket.emit);126 sinon.assert.calledWith(mockSocket.emit, '/api/connectionDeploy', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func);127 });128 });129 it('should handle an error from the connector server', () => {130 mockSocket.emit.withArgs('/api/connectionDeploy', connectionID, securityContextID, 'aGVsbG8gd29ybGQ=', undefined, sinon.match.func).yields(serializedError);131 return connection.deploy(mockSecurityContext, mockBusinessNetworkDefinition)132 .should.be.rejectedWith(TypeError, /such type error/);133 });134 });135 describe('#undeploy', () => {136 it('should send a undeploy call to the connector server', () => {137 mockSocket.emit.withArgs('/api/connectionUndeploy', connectionID, securityContextID, businessNetworkIdentifier, sinon.match.func).yields(null);138 return connection.undeploy(mockSecurityContext, businessNetworkIdentifier)139 .then(() => {140 sinon.assert.calledOnce(mockSocket.emit);141 sinon.assert.calledWith(mockSocket.emit, '/api/connectionUndeploy', connectionID, securityContextID, businessNetworkIdentifier, sinon.match.func);142 });143 });144 it('should handle an error from the connector server', () => {145 mockSocket.emit.withArgs('/api/connectionUndeploy', connectionID, securityContextID, businessNetworkIdentifier, sinon.match.func).yields(serializedError);146 return connection.undeploy(mockSecurityContext, businessNetworkIdentifier)147 .should.be.rejectedWith(TypeError, /such type error/);148 });149 });150 describe('#ping', () => {151 it('should send a ping call to the connector server', () => {152 mockSocket.emit.withArgs('/api/connectionPing', connectionID, securityContextID, sinon.match.func).yields(null);153 return connection.ping(mockSecurityContext)154 .then(() => {155 sinon.assert.calledOnce(mockSocket.emit);156 sinon.assert.calledWith(mockSocket.emit, '/api/connectionPing', connectionID, securityContextID, sinon.match.func);157 });158 });159 it('should handle an error from the connector server', () => {160 mockSocket.emit.withArgs('/api/connectionPing', connectionID, securityContextID, sinon.match.func).yields(serializedError);161 return connection.ping(mockSecurityContext)162 .should.be.rejectedWith(TypeError, /such type error/);163 });164 });165 describe('#queryChainCode', () => {166 const functionName = 'func1';167 const args = [ 'arg1', 'arg2', 'arg3' ];168 it('should send a queryChainCode call to the connector server', () => {169 mockSocket.emit.withArgs('/api/connectionQueryChainCode', connectionID, securityContextID, functionName, args, sinon.match.func).yields(null, 'hello world');170 return connection.queryChainCode(mockSecurityContext, functionName, args)171 .then((result) => {172 sinon.assert.calledOnce(mockSocket.emit);173 sinon.assert.calledWith(mockSocket.emit, '/api/connectionQueryChainCode', connectionID, securityContextID, functionName, args, sinon.match.func);174 Buffer.isBuffer(result).should.be.true;175 Buffer.from('hello world').compare(result).should.equal(0);176 });177 });178 it('should handle an error from the connector server', () => {179 mockSocket.emit.withArgs('/api/connectionQueryChainCode', connectionID, securityContextID, functionName, args, sinon.match.func).yields(serializedError);180 return connection.queryChainCode(mockSecurityContext, functionName, args)181 .should.be.rejectedWith(TypeError, /such type error/);182 });183 });184 describe('#invokeChainCode', () => {185 const functionName = 'func1';186 const args = [ 'arg1', 'arg2', 'arg3' ];187 it('should send a invokeChainCode call to the connector server', () => {188 mockSocket.emit.withArgs('/api/connectionInvokeChainCode', connectionID, securityContextID, functionName, args, sinon.match.func).yields(null);189 return connection.invokeChainCode(mockSecurityContext, functionName, args)190 .then(() => {191 sinon.assert.calledOnce(mockSocket.emit);192 sinon.assert.calledWith(mockSocket.emit, '/api/connectionInvokeChainCode', connectionID, securityContextID, functionName, args, sinon.match.func);193 });194 });195 it('should handle an error from the connector server', () => {196 mockSocket.emit.withArgs('/api/connectionInvokeChainCode', connectionID, securityContextID, functionName, args, sinon.match.func).yields(serializedError);197 return connection.invokeChainCode(mockSecurityContext, functionName, args)198 .should.be.rejectedWith(TypeError, /such type error/);199 });200 });201 describe('#createIdentity', () => {202 const userID = 'bob1';203 const options = {204 something: 'something',205 dark: 'side'206 };207 it('should send a createIdentity call to the connector server', () => {208 mockSocket.emit.withArgs('/api/connectionCreateIdentity', connectionID, securityContextID, userID, options, sinon.match.func).yields(null, {209 userID: userID,210 userSecret: 'w0ws3cret'211 });212 return connection.createIdentity(mockSecurityContext, userID, options)213 .then((result) => {214 sinon.assert.calledOnce(mockSocket.emit);215 sinon.assert.calledWith(mockSocket.emit, '/api/connectionCreateIdentity', connectionID, securityContextID, userID, options, sinon.match.func);216 result.should.deep.equal({217 userID: userID,218 userSecret: 'w0ws3cret'219 });220 });221 });222 it('should handle an error from the connector server', () => {223 mockSocket.emit.withArgs('/api/connectionCreateIdentity', connectionID, securityContextID, userID, options, sinon.match.func).yields(serializedError);224 return connection.createIdentity(mockSecurityContext, userID, options)225 .should.be.rejectedWith(TypeError, /such type error/);226 });227 });228 describe('#list', () => {229 it('should send a list call to the connector server', () => {230 mockSocket.emit.withArgs('/api/connectionList', connectionID, securityContextID, sinon.match.func).yields(null, ['org-acme-biznet1', 'org-acme-biznet2']);231 return connection.list(mockSecurityContext)232 .then((result) => {233 sinon.assert.calledOnce(mockSocket.emit);234 sinon.assert.calledWith(mockSocket.emit, '/api/connectionList', connectionID, securityContextID, sinon.match.func);235 result.should.deep.equal(['org-acme-biznet1', 'org-acme-biznet2']);236 });237 });238 it('should handle an error from the connector server', () => {239 mockSocket.emit.withArgs('/api/connectionList', connectionID, securityContextID, sinon.match.func).yields(serializedError);240 return connection.list(mockSecurityContext)241 .should.be.rejectedWith(TypeError, /such type error/);242 });243 });244 describe('#createTransactionId', () => {245 it('should send a list call to the connector server', () => {246 mockSocket.emit.withArgs('/api/connectionCreateTransactionId', connectionID, securityContextID, sinon.match.func).yields(null, ['32']);247 return connection.createTransactionId(mockSecurityContext)248 .then((result) => {249 sinon.assert.calledOnce(mockSocket.emit);250 sinon.assert.calledWith(mockSocket.emit, '/api/connectionCreateTransactionId', connectionID, securityContextID, sinon.match.func);251 result.should.deep.equal(['32']);252 });253 });254 it('should handle an error from the connector server', () => {255 mockSocket.emit.withArgs('/api/connectionCreateTransactionId', connectionID, securityContextID, sinon.match.func).yields(serializedError);256 return connection.createTransactionId(mockSecurityContext)257 .should.be.rejectedWith(TypeError, /such type error/);258 });259 });...

Full Screen

Full Screen

proxyconnectionmanager.js

Source:proxyconnectionmanager.js Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * You may obtain a copy of the License at5 *6 * http://www.apache.org/licenses/LICENSE-2.07 *8 * Unless required by applicable law or agreed to in writing, software9 * distributed under the License is distributed on an "AS IS" BASIS,10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11 * See the License for the specific language governing permissions and12 * limitations under the License.13 */14'use strict';15const ConnectionProfileManager = require('composer-common').ConnectionProfileManager;16const ProxyConnection = require('../lib/proxyconnection');17/* const ProxyConnectionManager = */ require('..');18const serializerr = require('serializerr');19const chai = require('chai');20chai.should();21chai.use(require('chai-as-promised'));22const proxyquire = require('proxyquire');23const sinon = require('sinon');24describe('ProxyConnectionManager', () => {25 const connectionProfile = 'defaultProfile';26 const businessNetworkIdentifier = 'org-acme-biznet';27 const connectionOptions = {28 type: 'embedded'29 };30 const connectionID = '3d382385-47a5-4be9-99b0-6b10166b9497';31 const serializedError = serializerr(new TypeError('such type error'));32 let mockSocketFactory;33 let mockSocket;34 let mockConnectionProfileManager;35 let ProxyConnectionManager;36 let connectionManager;37 let mockConnection;38 beforeEach(() => {39 mockConnectionProfileManager = sinon.createStubInstance(ConnectionProfileManager);40 mockSocket = {41 emit: sinon.stub(),42 once: sinon.stub(),43 on: sinon.stub()44 };45 // mockSocket.emit.throws(new Error('unexpected call'));46 // mockSocket.once.throws(new Error('unexpected call'));47 // mockSocket.on.throws(new Error('unexpected call'));48 mockSocketFactory = sinon.stub().returns(mockSocket);49 ProxyConnectionManager = proxyquire('../lib/proxyconnectionmanager', {50 'socket.io-client': mockSocketFactory51 });52 });53 describe('#setConnectorServerURL', () => {54 it('should change the URL used to connect to the connector server', () => {55 ProxyConnectionManager.setConnectorServerURL('http://blah.com:2393');56 mockSocket.on.withArgs('connect').returns();57 mockSocket.on.withArgs('disconnect').returns();58 new ProxyConnectionManager(mockConnectionProfileManager);59 sinon.assert.calledOnce(mockSocketFactory);60 sinon.assert.calledWith(mockSocketFactory, 'http://blah.com:2393');61 });62 });63 describe('#constructor', () => {64 let connectionManager;65 beforeEach(() => {66 mockSocket.on.withArgs('connect').returns();67 mockSocket.on.withArgs('disconnect').returns();68 connectionManager = new ProxyConnectionManager(mockConnectionProfileManager);69 });70 it('should create a new socket connection and listen for a connect event', () => {71 sinon.assert.calledOnce(mockSocketFactory);72 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');73 // Trigger the connect callback.74 connectionManager.connected.should.be.false;75 mockSocket.on.args[0][0].should.equal('connect');76 mockSocket.on.args[0][1]();77 connectionManager.connected.should.be.true;78 });79 it('should create a new socket connection and listen for a disconnect event', () => {80 sinon.assert.calledOnce(mockSocketFactory);81 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');82 // Trigger the disconnect callback.83 connectionManager.connected = true;84 mockSocket.on.args[1][0].should.equal('disconnect');85 mockSocket.on.args[1][1]();86 connectionManager.connected.should.be.false;87 });88 });89 describe('#ensureConnected', () => {90 let connectionManager;91 beforeEach(() => {92 mockSocket.on.withArgs('connect').returns();93 mockSocket.on.withArgs('disconnect').returns();94 connectionManager = new ProxyConnectionManager(mockConnectionProfileManager);95 });96 it('should do nothing if already connected', () => {97 connectionManager.connected = true;98 return connectionManager.ensureConnected();99 });100 it('should wait for a connection if not connected', () => {101 mockSocket.once.withArgs('connect').yields();102 connectionManager.connected = false;103 return connectionManager.ensureConnected()104 .then(() => {105 sinon.assert.calledOnce(mockSocket.once);106 sinon.assert.calledWith(mockSocket.once, 'connect');107 });108 });109 });110 describe('#importIdentity', () => {111 beforeEach(() => {112 mockConnection = sinon.createStubInstance(ProxyConnection);113 mockConnection.connectionID = connectionID;114 mockConnection.socket = mockSocket;115 mockSocket.on.withArgs('connect').returns();116 mockSocket.on.withArgs('disconnect').returns();117 connectionManager = new ProxyConnectionManager(mockConnectionProfileManager);118 connectionManager.connected = true;119 });120 it('should send a importIdentity call to the connector server', () => {121 mockSocket.emit.withArgs('/api/connectionManagerImportIdentity', connectionProfile, connectionOptions, 'bob1', 'public key', 'private key', sinon.match.func).yields(null);122 sinon.stub(ProxyConnectionManager, 'createConnection').returns(mockConnection);123 return connectionManager.importIdentity(connectionProfile, connectionOptions, 'bob1', 'public key', 'private key')124 .then(() => {125 sinon.assert.calledOnce(mockSocket.emit);126 sinon.assert.calledWith(mockSocket.emit, '/api/connectionManagerImportIdentity', connectionProfile, connectionOptions, 'bob1', 'public key', 'private key', sinon.match.func);127 sinon.assert.calledTwice(mockSocket.on);128 });129 });130 it('should handle an error from the connector server', () => {131 mockSocket.emit.withArgs('/api/connectionManagerImportIdentity', connectionProfile, connectionOptions, 'bob1', 'public key', 'private key', sinon.match.func).yields(serializedError);132 return connectionManager.importIdentity(connectionProfile, connectionOptions, 'bob1', 'public key', 'private key')133 .should.be.rejectedWith(TypeError, /such type error/);134 });135 });136 describe('#exportIdentity', () => {137 beforeEach(() => {138 mockConnection = sinon.createStubInstance(ProxyConnection);139 mockConnection.connectionID = connectionID;140 mockConnection.socket = mockSocket;141 mockSocket.on.withArgs('connect').returns();142 mockSocket.on.withArgs('disconnect').returns();143 connectionManager = new ProxyConnectionManager(mockConnectionProfileManager);144 connectionManager.connected = true;145 });146 it('should send exportIdentity call to connector server', function() {147 const expected = {148 certificate: 'CERTIFICATE',149 privateKey: 'PRIVATE_KEY'150 };151 mockSocket.emit.withArgs('/api/connectionManagerExportIdentity', connectionProfile, connectionOptions, 'bob1', sinon.match.func).yields(null, expected);152 sinon.stub(ProxyConnectionManager, 'createConnection').returns(mockConnection);153 return connectionManager.exportIdentity(connectionProfile, connectionOptions, 'bob1')154 .should.become(expected);155 });156 it('should handle an error from the connector server', () => {157 mockSocket.emit.withArgs('/api/connectionManagerExportIdentity', connectionProfile, connectionOptions, 'bob1', sinon.match.func).yields(serializedError);158 return connectionManager.exportIdentity(connectionProfile, connectionOptions, 'bob1')159 .should.be.rejectedWith(TypeError, /such type error/);160 });161 });162 describe('#connect', () => {163 beforeEach(() => {164 mockConnection = sinon.createStubInstance(ProxyConnection);165 mockConnection.connectionID = connectionID;166 mockConnection.socket = mockSocket;167 mockSocket.on.withArgs('connect').returns();168 mockSocket.on.withArgs('disconnect').returns();169 connectionManager = new ProxyConnectionManager(mockConnectionProfileManager);170 connectionManager.connected = true;171 });172 it('should send a connect call to the connector server', () => {173 mockSocket.emit.withArgs('/api/connectionManagerConnect', connectionProfile, businessNetworkIdentifier, connectionOptions, sinon.match.func).yields(null, connectionID);174 sinon.stub(ProxyConnectionManager, 'createConnection').returns(mockConnection);175 mockSocket.on.withArgs('events', sinon.match.func).yields(connectionID, [{'event': 'event1'}, {'evnet': 'event2'}]);176 return connectionManager.connect(connectionProfile, businessNetworkIdentifier, connectionOptions)177 .then((connection) => {178 sinon.assert.calledOnce(mockSocket.emit);179 sinon.assert.calledWith(mockSocket.emit, '/api/connectionManagerConnect', connectionProfile, businessNetworkIdentifier, connectionOptions, sinon.match.func);180 connection.should.be.an.instanceOf(ProxyConnection);181 connection.socket.should.equal(mockSocket);182 connection.connectionID.should.equal(connectionID);183 sinon.assert.calledThrice(mockSocket.on);184 sinon.assert.calledWith(mockSocket.on, 'events', sinon.match.func);185 sinon.assert.calledWith(mockConnection.emit, 'events', [{'event': 'event1'}, {'evnet': 'event2'}]);186 });187 });188 it('should not emit events if connectionID and myConnectionID dont match', () => {189 mockSocket.emit.withArgs('/api/connectionManagerConnect', connectionProfile, businessNetworkIdentifier, connectionOptions, sinon.match.func).yields(null, connectionID);190 sinon.stub(ProxyConnectionManager, 'createConnection').returns(mockConnection);191 mockSocket.on.withArgs('events', sinon.match.func).yields('myConnectionID', '[{"event": "event1"}, {"evnet": "event2"}]');192 return connectionManager.connect(connectionProfile, businessNetworkIdentifier, connectionOptions)193 .then((connection) => {194 sinon.assert.calledOnce(mockSocket.emit);195 sinon.assert.calledWith(mockSocket.emit, '/api/connectionManagerConnect', connectionProfile, businessNetworkIdentifier, connectionOptions, sinon.match.func);196 connection.should.be.an.instanceOf(ProxyConnection);197 connection.socket.should.equal(mockSocket);198 connection.connectionID.should.equal(connectionID);199 sinon.assert.calledThrice(mockSocket.on);200 sinon.assert.calledWith(mockSocket.on, 'events', sinon.match.func);201 sinon.assert.notCalled(connection.emit);202 });203 });204 it('should handle an error from the connector server', () => {205 mockSocket.emit.withArgs('/api/connectionManagerConnect', connectionProfile, businessNetworkIdentifier, connectionOptions, sinon.match.func).yields(serializedError);206 return connectionManager.connect(connectionProfile, businessNetworkIdentifier, connectionOptions)207 .should.be.rejectedWith(TypeError, /such type error/);208 });209 });210 describe('#createConnection', () => {211 it('should create an instance of ProxyConnection', () => {212 let cm = ProxyConnectionManager.createConnection(connectionManager, 'profile', 'businessNetworkIdentifier', mockSocket, connectionID);213 cm.should.be.an.instanceOf(ProxyConnection);214 });215 });...

Full Screen

Full Screen

proxybusinessnetworkcardstore.js

Source:proxybusinessnetworkcardstore.js Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * You may obtain a copy of the License at5 *6 * http://www.apache.org/licenses/LICENSE-2.07 *8 * Unless required by applicable law or agreed to in writing, software9 * distributed under the License is distributed on an "AS IS" BASIS,10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11 * See the License for the specific language governing permissions and12 * limitations under the License.13 */14'use strict';15/* const ProxyBusinessNetworkCardStore = */16require('..');17const serializerr = require('serializerr');18const IdCard = require('composer-common').IdCard;19const chai = require('chai');20chai.should();21chai.use(require('chai-as-promised'));22const proxyquire = require('proxyquire');23const sinon = require('sinon');24describe('ProxyBusinessNetworkCardStore', () => {25 const cardName = 'myCard';26 const card = new IdCard({userName : 'banana'}, {name : 'profileOne'});27 const cardOne = new IdCard({userName : 'bob'}, {name : 'profileTwo'});28 const serializedError = serializerr(new TypeError('such type error'));29 let mockSocketFactory;30 let mockSocket;31 let ProxyBusinessNetworkCardStore;32 let businessNetworkCardStore;33 beforeEach(() => {34 mockSocket = {35 emit : sinon.stub(),36 once : sinon.stub(),37 on : sinon.stub()38 };39 mockSocketFactory = sinon.stub().returns(mockSocket);40 ProxyBusinessNetworkCardStore = proxyquire('../lib/proxybusinessnetworkcardstore', {41 'socket.io-client' : mockSocketFactory42 });43 });44 describe('#setConnectorServerURL', () => {45 it('should change the URL used to connect to the connector server', () => {46 ProxyBusinessNetworkCardStore.setConnectorServerURL('http://blah.com:2393');47 mockSocket.on.withArgs('connect').returns();48 mockSocket.on.withArgs('disconnect').returns();49 new ProxyBusinessNetworkCardStore();50 sinon.assert.calledOnce(mockSocketFactory);51 sinon.assert.calledWith(mockSocketFactory, 'http://blah.com:2393');52 });53 });54 describe('#constructor', () => {55 let businessNetworkCardStore;56 beforeEach(() => {57 mockSocket.on.withArgs('connect').returns();58 mockSocket.on.withArgs('disconnect').returns();59 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();60 });61 it('should create a new socket connection and listen for a connect event', () => {62 sinon.assert.calledOnce(mockSocketFactory);63 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');64 // Trigger the connect callback.65 businessNetworkCardStore.connected.should.be.false;66 mockSocket.on.args[0][0].should.equal('connect');67 mockSocket.on.args[0][1]();68 businessNetworkCardStore.connected.should.be.true;69 });70 it('should create a new socket connection and listen for a disconnect event', () => {71 sinon.assert.calledOnce(mockSocketFactory);72 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');73 // Trigger the disconnect callback.74 businessNetworkCardStore.connected = true;75 mockSocket.on.args[1][0].should.equal('disconnect');76 mockSocket.on.args[1][1]();77 businessNetworkCardStore.connected.should.be.false;78 });79 });80 describe('#ensureConnected', () => {81 let connectionManager;82 beforeEach(() => {83 mockSocket.on.withArgs('connect').returns();84 mockSocket.on.withArgs('disconnect').returns();85 connectionManager = new ProxyBusinessNetworkCardStore();86 });87 it('should do nothing if already connected', () => {88 connectionManager.connected = true;89 return connectionManager.ensureConnected();90 });91 it('should wait for a connection if not connected', () => {92 mockSocket.once.withArgs('connect').yields();93 connectionManager.connected = false;94 return connectionManager.ensureConnected()95 .then(() => {96 sinon.assert.calledOnce(mockSocket.once);97 sinon.assert.calledWith(mockSocket.once, 'connect');98 });99 });100 });101 describe('#get', () => {102 beforeEach(() => {103 mockSocket.on.withArgs('connect').returns();104 mockSocket.on.withArgs('disconnect').returns();105 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();106 businessNetworkCardStore.connected = true;107 });108 it('should send a get call to the connector server', () => {109 mockSocket.emit.withArgs('/api/businessNetworkCardStoreGet', cardName, sinon.match.func).yields(null, card);110 return businessNetworkCardStore.get(cardName)111 .then((result) => {112 sinon.assert.calledOnce(mockSocket.emit);113 sinon.assert.calledWith(mockSocket.emit, '/api/businessNetworkCardStoreGet', cardName, sinon.match.func);114 sinon.assert.calledTwice(mockSocket.on);115 result.should.deep.equal(card);116 });117 });118 it('should handle an error from the connector server', () => {119 mockSocket.emit.withArgs('/api/businessNetworkCardStoreGet', cardName, sinon.match.func).yields(serializedError);120 return businessNetworkCardStore.get(cardName)121 .should.be.rejectedWith(TypeError, /such type error/);122 });123 });124 describe('#has', () => {125 beforeEach(() => {126 mockSocket.on.withArgs('connect').returns();127 mockSocket.on.withArgs('disconnect').returns();128 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();129 businessNetworkCardStore.connected = true;130 });131 it('should send a has call to the connector server', () => {132 mockSocket.emit.withArgs('/api/businessNetworkCardStoreHas', cardName, sinon.match.func).yields(null, true);133 return businessNetworkCardStore.has(cardName)134 .then((result) => {135 sinon.assert.calledOnce(mockSocket.emit);136 sinon.assert.calledWith(mockSocket.emit, '/api/businessNetworkCardStoreHas', cardName, sinon.match.func);137 sinon.assert.calledTwice(mockSocket.on);138 result.should.equal(true);139 });140 });141 it('should handle an error from the connector server', () => {142 mockSocket.emit.withArgs('/api/businessNetworkCardStoreHas', cardName, sinon.match.func).yields(serializedError);143 return businessNetworkCardStore.has(cardName)144 .should.be.rejectedWith(TypeError, /such type error/);145 });146 });147 describe('#put', () => {148 beforeEach(() => {149 mockSocket.on.withArgs('connect').returns();150 mockSocket.on.withArgs('disconnect').returns();151 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();152 businessNetworkCardStore.connected = true;153 });154 it('should send a put call to the connector server', () => {155 mockSocket.emit.withArgs('/api/businessNetworkCardStorePut', cardName, card, sinon.match.func).yields(null);156 return businessNetworkCardStore.put(cardName, card)157 .then(() => {158 sinon.assert.calledOnce(mockSocket.emit);159 sinon.assert.calledWith(mockSocket.emit, '/api/businessNetworkCardStorePut', cardName, card, sinon.match.func);160 sinon.assert.calledTwice(mockSocket.on);161 });162 });163 it('should handle an error from the connector server', () => {164 mockSocket.emit.withArgs('/api/businessNetworkCardStorePut', cardName, card, sinon.match.func).yields(serializedError);165 return businessNetworkCardStore.put(cardName, card)166 .should.be.rejectedWith(TypeError, /such type error/);167 });168 });169 describe('#getAll', () => {170 beforeEach(() => {171 mockSocket.on.withArgs('connect').returns();172 mockSocket.on.withArgs('disconnect').returns();173 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();174 businessNetworkCardStore.connected = true;175 });176 it('should send a getAll call to the connector server', () => {177 let cardObject = {178 'cardOne' : card,179 'cardTwo' : cardOne180 };181 mockSocket.emit.withArgs('/api/businessNetworkCardStoreGetAll', sinon.match.func).yields(null, cardObject);182 return businessNetworkCardStore.getAll()183 .then((result) => {184 sinon.assert.calledOnce(mockSocket.emit);185 sinon.assert.calledWith(mockSocket.emit, '/api/businessNetworkCardStoreGetAll', sinon.match.func);186 sinon.assert.calledTwice(mockSocket.on);187 result.size.should.equal(2);188 result.get('cardOne').should.deep.equal(card);189 result.get('cardTwo').should.deep.equal(cardOne);190 });191 });192 it('should handle an error from the connector server', () => {193 mockSocket.emit.withArgs('/api/businessNetworkCardStoreGetAll', sinon.match.func).yields(serializedError);194 return businessNetworkCardStore.getAll()195 .should.be.rejectedWith(TypeError, /such type error/);196 });197 });198 describe('#delete', () => {199 beforeEach(() => {200 mockSocket.on.withArgs('connect').returns();201 mockSocket.on.withArgs('disconnect').returns();202 businessNetworkCardStore = new ProxyBusinessNetworkCardStore();203 businessNetworkCardStore.connected = true;204 });205 it('should send a delete call to the connector server', () => {206 mockSocket.emit.withArgs('/api/businessNetworkCardStoreDelete', cardName, sinon.match.func).yields(null);207 return businessNetworkCardStore.delete(cardName)208 .then(() => {209 sinon.assert.calledOnce(mockSocket.emit);210 sinon.assert.calledWith(mockSocket.emit, '/api/businessNetworkCardStoreDelete', cardName, sinon.match.func);211 sinon.assert.calledTwice(mockSocket.on);212 });213 });214 it('should handle an error from the connector server', () => {215 mockSocket.emit.withArgs('/api/businessNetworkCardStoreDelete', cardName, sinon.match.func).yields(serializedError);216 return businessNetworkCardStore.delete(cardName)217 .should.be.rejectedWith(TypeError, /such type error/);218 });219 });...

Full Screen

Full Screen

proxyconnectionprofilestore.js

Source:proxyconnectionprofilestore.js Github

copy

Full Screen

1/*2 * Licensed under the Apache License, Version 2.0 (the "License");3 * you may not use this file except in compliance with the License.4 * You may obtain a copy of the License at5 *6 * http://www.apache.org/licenses/LICENSE-2.07 *8 * Unless required by applicable law or agreed to in writing, software9 * distributed under the License is distributed on an "AS IS" BASIS,10 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11 * See the License for the specific language governing permissions and12 * limitations under the License.13 */14'use strict';15/* const ProxyConnectionProfileStore = */ require('..');16const serializerr = require('serializerr');17const chai = require('chai');18chai.should();19chai.use(require('chai-as-promised'));20const proxyquire = require('proxyquire');21const sinon = require('sinon');22describe('ProxyConnectionProfileStore', () => {23 const connectionProfile = 'defaultProfile';24 const connectionOptions = {25 type: 'embedded'26 };27 const otherConnectionOptions = {28 type: 'web'29 };30 const serializedError = serializerr(new TypeError('such type error'));31 let mockSocketFactory;32 let mockSocket;33 let ProxyConnectionProfileStore;34 let connectionProfileStore;35 beforeEach(() => {36 mockSocket = {37 emit: sinon.stub(),38 once: sinon.stub(),39 on: sinon.stub()40 };41 // mockSocket.emit.throws(new Error('unexpected call'));42 // mockSocket.once.throws(new Error('unexpected call'));43 // mockSocket.on.throws(new Error('unexpected call'));44 mockSocketFactory = sinon.stub().returns(mockSocket);45 ProxyConnectionProfileStore = proxyquire('../lib/proxyconnectionprofilestore', {46 'socket.io-client': mockSocketFactory47 });48 });49 describe('#setConnectorServerURL', () => {50 it('should change the URL used to connect to the connector server', () => {51 ProxyConnectionProfileStore.setConnectorServerURL('http://blah.com:2393');52 mockSocket.on.withArgs('connect').returns();53 mockSocket.on.withArgs('disconnect').returns();54 new ProxyConnectionProfileStore();55 sinon.assert.calledOnce(mockSocketFactory);56 sinon.assert.calledWith(mockSocketFactory, 'http://blah.com:2393');57 });58 });59 describe('#constructor', () => {60 let connectionProfileStore;61 beforeEach(() => {62 mockSocket.on.withArgs('connect').returns();63 mockSocket.on.withArgs('disconnect').returns();64 connectionProfileStore = new ProxyConnectionProfileStore();65 });66 it('should create a new socket connection and listen for a connect event', () => {67 sinon.assert.calledOnce(mockSocketFactory);68 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');69 // Trigger the connect callback.70 connectionProfileStore.connected.should.be.false;71 mockSocket.on.args[0][0].should.equal('connect');72 mockSocket.on.args[0][1]();73 connectionProfileStore.connected.should.be.true;74 });75 it('should create a new socket connection and listen for a disconnect event', () => {76 sinon.assert.calledOnce(mockSocketFactory);77 sinon.assert.calledWith(mockSocketFactory, 'http://localhost:15699');78 // Trigger the disconnect callback.79 connectionProfileStore.connected = true;80 mockSocket.on.args[1][0].should.equal('disconnect');81 mockSocket.on.args[1][1]();82 connectionProfileStore.connected.should.be.false;83 });84 });85 describe('#ensureConnected', () => {86 let connectionManager;87 beforeEach(() => {88 mockSocket.on.withArgs('connect').returns();89 mockSocket.on.withArgs('disconnect').returns();90 connectionManager = new ProxyConnectionProfileStore();91 });92 it('should do nothing if already connected', () => {93 connectionManager.connected = true;94 return connectionManager.ensureConnected();95 });96 it('should wait for a connection if not connected', () => {97 mockSocket.once.withArgs('connect').yields();98 connectionManager.connected = false;99 return connectionManager.ensureConnected()100 .then(() => {101 sinon.assert.calledOnce(mockSocket.once);102 sinon.assert.calledWith(mockSocket.once, 'connect');103 });104 });105 });106 describe('#load', () => {107 beforeEach(() => {108 mockSocket.on.withArgs('connect').returns();109 mockSocket.on.withArgs('disconnect').returns();110 connectionProfileStore = new ProxyConnectionProfileStore();111 connectionProfileStore.connected = true;112 });113 it('should send a load call to the connector server', () => {114 mockSocket.emit.withArgs('/api/connectionProfileStoreLoad', connectionProfile, sinon.match.func).yields(null, connectionOptions);115 return connectionProfileStore.load(connectionProfile)116 .then((result) => {117 sinon.assert.calledOnce(mockSocket.emit);118 sinon.assert.calledWith(mockSocket.emit, '/api/connectionProfileStoreLoad', connectionProfile, sinon.match.func);119 sinon.assert.calledTwice(mockSocket.on);120 result.should.deep.equal(connectionOptions);121 });122 });123 it('should handle an error from the connector server', () => {124 mockSocket.emit.withArgs('/api/connectionProfileStoreLoad', connectionProfile, sinon.match.func).yields(serializedError);125 return connectionProfileStore.load(connectionProfile)126 .should.be.rejectedWith(TypeError, /such type error/);127 });128 });129 describe('#save', () => {130 beforeEach(() => {131 mockSocket.on.withArgs('connect').returns();132 mockSocket.on.withArgs('disconnect').returns();133 connectionProfileStore = new ProxyConnectionProfileStore();134 connectionProfileStore.connected = true;135 });136 it('should send a save call to the connector server', () => {137 mockSocket.emit.withArgs('/api/connectionProfileStoreSave', connectionProfile, connectionOptions, sinon.match.func).yields(null);138 return connectionProfileStore.save(connectionProfile, connectionOptions)139 .then(() => {140 sinon.assert.calledOnce(mockSocket.emit);141 sinon.assert.calledWith(mockSocket.emit, '/api/connectionProfileStoreSave', connectionProfile, connectionOptions, sinon.match.func);142 sinon.assert.calledTwice(mockSocket.on);143 });144 });145 it('should handle an error from the connector server', () => {146 mockSocket.emit.withArgs('/api/connectionProfileStoreSave', connectionProfile, connectionOptions, sinon.match.func).yields(serializedError);147 return connectionProfileStore.save(connectionProfile, connectionOptions)148 .should.be.rejectedWith(TypeError, /such type error/);149 });150 });151 describe('#loadAll', () => {152 beforeEach(() => {153 mockSocket.on.withArgs('connect').returns();154 mockSocket.on.withArgs('disconnect').returns();155 connectionProfileStore = new ProxyConnectionProfileStore();156 connectionProfileStore.connected = true;157 });158 it('should send a loadAll call to the connector server', () => {159 mockSocket.emit.withArgs('/api/connectionProfileStoreLoadAll', sinon.match.func).yields(null, [ connectionOptions, otherConnectionOptions ]);160 return connectionProfileStore.loadAll()161 .then((result) => {162 sinon.assert.calledOnce(mockSocket.emit);163 sinon.assert.calledWith(mockSocket.emit, '/api/connectionProfileStoreLoadAll', sinon.match.func);164 sinon.assert.calledTwice(mockSocket.on);165 result.should.deep.equal([ connectionOptions, otherConnectionOptions ]);166 });167 });168 it('should handle an error from the connector server', () => {169 mockSocket.emit.withArgs('/api/connectionProfileStoreLoadAll', sinon.match.func).yields(serializedError);170 return connectionProfileStore.loadAll()171 .should.be.rejectedWith(TypeError, /such type error/);172 });173 });174 describe('#delete', () => {175 beforeEach(() => {176 mockSocket.on.withArgs('connect').returns();177 mockSocket.on.withArgs('disconnect').returns();178 connectionProfileStore = new ProxyConnectionProfileStore();179 connectionProfileStore.connected = true;180 });181 it('should send a delete call to the connector server', () => {182 mockSocket.emit.withArgs('/api/connectionProfileStoreDelete', connectionProfile, sinon.match.func).yields(null);183 return connectionProfileStore.delete(connectionProfile)184 .then(() => {185 sinon.assert.calledOnce(mockSocket.emit);186 sinon.assert.calledWith(mockSocket.emit, '/api/connectionProfileStoreDelete', connectionProfile, sinon.match.func);187 sinon.assert.calledTwice(mockSocket.on);188 });189 });190 it('should handle an error from the connector server', () => {191 mockSocket.emit.withArgs('/api/connectionProfileStoreDelete', connectionProfile, sinon.match.func).yields(serializedError);192 return connectionProfileStore.delete(connectionProfile)193 .should.be.rejectedWith(TypeError, /such type error/);194 });195 });...

Full Screen

Full Screen

sender.test.js

Source:sender.test.js Github

copy

Full Screen

...39 describe('#send', () => {40 it('compresses data if compress option is enabled', (done) => {41 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });42 let count = 0;43 const mockSocket = new MockSocket({44 write: (data) => {45 assert.strictEqual(data[0] & 0x40, 0x40);46 if (++count === 3) done();47 }48 });49 const sender = new Sender(mockSocket, {50 'permessage-deflate': perMessageDeflate51 });52 perMessageDeflate.accept([{}]);53 const options = { compress: true, fin: true };54 const array = new Uint8Array([0x68, 0x69]);55 sender.send(array.buffer, options);56 sender.send(array, options);57 sender.send('hi', options);58 });59 it('does not compress data for small payloads', (done) => {60 const perMessageDeflate = new PerMessageDeflate();61 const mockSocket = new MockSocket({62 write: (data) => {63 assert.notStrictEqual(data[0] & 0x40, 0x40);64 done();65 }66 });67 const sender = new Sender(mockSocket, {68 'permessage-deflate': perMessageDeflate69 });70 perMessageDeflate.accept([{}]);71 sender.send('hi', { compress: true, fin: true });72 });73 it('compresses all frames in a fragmented message', (done) => {74 const chunks = [];75 const perMessageDeflate = new PerMessageDeflate({ threshold: 3 });76 const mockSocket = new MockSocket({77 write: (chunk) => {78 chunks.push(chunk);79 if (chunks.length !== 4) return;80 assert.strictEqual(chunks[0].length, 2);81 assert.strictEqual(chunks[0][0] & 0x40, 0x40);82 assert.strictEqual(chunks[1].length, 9);83 assert.strictEqual(chunks[2].length, 2);84 assert.strictEqual(chunks[2][0] & 0x40, 0x00);85 assert.strictEqual(chunks[3].length, 4);86 done();87 }88 });89 const sender = new Sender(mockSocket, {90 'permessage-deflate': perMessageDeflate91 });92 perMessageDeflate.accept([{}]);93 sender.send('123', { compress: true, fin: false });94 sender.send('12', { compress: true, fin: true });95 });96 it('compresses no frames in a fragmented message', (done) => {97 const chunks = [];98 const perMessageDeflate = new PerMessageDeflate({ threshold: 3 });99 const mockSocket = new MockSocket({100 write: (chunk) => {101 chunks.push(chunk);102 if (chunks.length !== 4) return;103 assert.strictEqual(chunks[0].length, 2);104 assert.strictEqual(chunks[0][0] & 0x40, 0x00);105 assert.strictEqual(chunks[1].length, 2);106 assert.strictEqual(chunks[2].length, 2);107 assert.strictEqual(chunks[2][0] & 0x40, 0x00);108 assert.strictEqual(chunks[3].length, 3);109 done();110 }111 });112 const sender = new Sender(mockSocket, {113 'permessage-deflate': perMessageDeflate114 });115 perMessageDeflate.accept([{}]);116 sender.send('12', { compress: true, fin: false });117 sender.send('123', { compress: true, fin: true });118 });119 it('compresses empty buffer as first fragment', (done) => {120 const chunks = [];121 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });122 const mockSocket = new MockSocket({123 write: (chunk) => {124 chunks.push(chunk);125 if (chunks.length !== 4) return;126 assert.strictEqual(chunks[0].length, 2);127 assert.strictEqual(chunks[0][0] & 0x40, 0x40);128 assert.strictEqual(chunks[1].length, 5);129 assert.strictEqual(chunks[2].length, 2);130 assert.strictEqual(chunks[2][0] & 0x40, 0x00);131 assert.strictEqual(chunks[3].length, 6);132 done();133 }134 });135 const sender = new Sender(mockSocket, {136 'permessage-deflate': perMessageDeflate137 });138 perMessageDeflate.accept([{}]);139 sender.send(Buffer.alloc(0), { compress: true, fin: false });140 sender.send('data', { compress: true, fin: true });141 });142 it('compresses empty buffer as last fragment', (done) => {143 const chunks = [];144 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });145 const mockSocket = new MockSocket({146 write: (chunk) => {147 chunks.push(chunk);148 if (chunks.length !== 4) return;149 assert.strictEqual(chunks[0].length, 2);150 assert.strictEqual(chunks[0][0] & 0x40, 0x40);151 assert.strictEqual(chunks[1].length, 10);152 assert.strictEqual(chunks[2].length, 2);153 assert.strictEqual(chunks[2][0] & 0x40, 0x00);154 assert.strictEqual(chunks[3].length, 1);155 done();156 }157 });158 const sender = new Sender(mockSocket, {159 'permessage-deflate': perMessageDeflate160 });161 perMessageDeflate.accept([{}]);162 sender.send('data', { compress: true, fin: false });163 sender.send(Buffer.alloc(0), { compress: true, fin: true });164 });165 });166 describe('#ping', () => {167 it('works with multiple types of data', (done) => {168 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });169 let count = 0;170 const mockSocket = new MockSocket({171 write: (data) => {172 if (++count < 3) return;173 if (count % 2) {174 assert.ok(data.equals(Buffer.from([0x89, 0x02])));175 } else {176 assert.ok(data.equals(Buffer.from([0x68, 0x69])));177 }178 if (count === 8) done();179 }180 });181 const sender = new Sender(mockSocket, {182 'permessage-deflate': perMessageDeflate183 });184 perMessageDeflate.accept([{}]);185 const array = new Uint8Array([0x68, 0x69]);186 sender.send('foo', { compress: true, fin: true });187 sender.ping(array.buffer, false);188 sender.ping(array, false);189 sender.ping('hi', false);190 });191 });192 describe('#pong', () => {193 it('works with multiple types of data', (done) => {194 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });195 let count = 0;196 const mockSocket = new MockSocket({197 write: (data) => {198 if (++count < 3) return;199 if (count % 2) {200 assert.ok(data.equals(Buffer.from([0x8a, 0x02])));201 } else {202 assert.ok(data.equals(Buffer.from([0x68, 0x69])));203 }204 if (count === 8) done();205 }206 });207 const sender = new Sender(mockSocket, {208 'permessage-deflate': perMessageDeflate209 });210 perMessageDeflate.accept([{}]);211 const array = new Uint8Array([0x68, 0x69]);212 sender.send('foo', { compress: true, fin: true });213 sender.pong(array.buffer, false);214 sender.pong(array, false);215 sender.pong('hi', false);216 });217 });218 describe('#close', () => {219 it('throws an error if the first argument is invalid', () => {220 const mockSocket = new MockSocket();221 const sender = new Sender(mockSocket);222 assert.throws(223 () => sender.close('error'),224 /^TypeError: First argument must be a valid error code number$/225 );226 assert.throws(227 () => sender.close(1004),228 /^TypeError: First argument must be a valid error code number$/229 );230 });231 it('throws an error if the message is greater than 123 bytes', () => {232 const mockSocket = new MockSocket();233 const sender = new Sender(mockSocket);234 assert.throws(235 () => sender.close(1000, 'a'.repeat(124)),236 /^RangeError: The message must not be greater than 123 bytes$/237 );238 });239 it('should consume all data before closing', (done) => {240 const perMessageDeflate = new PerMessageDeflate({ threshold: 0 });241 let count = 0;242 const mockSocket = new MockSocket({243 write: (data, cb) => {244 count++;245 if (cb) cb();246 }247 });248 const sender = new Sender(mockSocket, {249 'permessage-deflate': perMessageDeflate250 });251 perMessageDeflate.accept([{}]);252 sender.send('foo', { compress: true, fin: true });253 sender.send('bar', { compress: true, fin: true });254 sender.send('baz', { compress: true, fin: true });255 sender.close(1000, undefined, false, () => {256 assert.strictEqual(count, 8);...

Full Screen

Full Screen

test_websocket.js

Source:test_websocket.js Github

copy

Full Screen

...41 };42};43describe('SocketReconnect', function() {44 const mockSocketManager = MockWebSocketManager();45 const mockSocket = ()=>mockSocketManager.getMockSocket();46 const expectMockSocketCallCount = (count)=>expect(mockSocketManager.getMockSocket_callCount()).toBe(count);47 let socket;48 beforeEach(function() {49 socket = mockSocketManager.setup(SocketReconnect, {});50 });51 afterEach(function() {52 mockSocketManager.teardown();53 socket = undefined;54 });55 it('Should call onConnected on creation/connection',()=>{56 expect(socket.onConnected).not.toHaveBeenCalled();57 mockSocket().onopen();58 expect(socket.onConnected).toHaveBeenCalled();59 });60 it('Should call onMessage when a message is received/decoded',()=>{61 mockSocket().onopen();62 expect(socket.onMessage).not.toHaveBeenCalled();63 mockSocket().onmessage({data: 'Hello World\n'});64 expect(socket.decodeMessages).toHaveBeenCalled();65 expect(socket.onMessage).toHaveBeenCalledWith('Hello World');66 });67 it('Should call send when a message is sent (but not when disconnected)',()=>{68 expect(mockSocket().send).not.toHaveBeenCalled();69 socket.send('Hello World');70 expect(mockSocket().send).not.toHaveBeenCalled();71 mockSocket().onopen();72 socket.send('Hello World');73 expect(mockSocket().send).toHaveBeenCalledWith('Hello World\n');74 mockSocket().onclose();75 mockSocket().send.calls.reset();76 socket.send('Hello Again');77 expect(mockSocket().send).not.toHaveBeenCalled();78 });79 it('Should attempt to reconnect when disconnected',()=>{80 mockSocket().onopen();81 expect(socket.onDisconnected).not.toHaveBeenCalled();82 mockSocket().onclose();83 expect(socket.onDisconnected).toHaveBeenCalled();84 let previous_mockSocket = mockSocket();85 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS - 1);86 expect(mockSocket()).toBe(previous_mockSocket);87 expectMockSocketCallCount(1);88 jasmine.clock().tick(2);89 expectMockSocketCallCount(2);90 expect(mockSocket()).not.toBe(previous_mockSocket);91 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS);92 expectMockSocketCallCount(3);93 mockSocket().onopen();94 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS);95 expectMockSocketCallCount(3);96 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS);97 expectMockSocketCallCount(3);98 });99 it('Should attempt to reconnect even if first connection fails',()=>{100 expect(socket.onConnected).not.toHaveBeenCalled();101 expectMockSocketCallCount(1);102 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS + 1);103 expectMockSocketCallCount(2);104 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS + 1);105 expectMockSocketCallCount(3);106 mockSocket().onopen();107 expect(socket.onConnected).toHaveBeenCalled();108 jasmine.clock().tick(DISCONNECTED_RETRY_INTERVAL_MS + 1);109 expectMockSocketCallCount(3);110 });111 // TODO: Test addOnMessageListener/removeOnMessageListener112});113describe('JsonSocketReconnect', function() {114 const mockSocketManager = MockWebSocketManager();115 const mockSocket = ()=>mockSocketManager.getMockSocket();116 const expectMockSocketCallCount = (count)=>expect(mockSocketManager.getMockSocket_callCount()).toBe(count);117 let socket;118 beforeEach(function() {119 socket = mockSocketManager.setup(JsonSocketReconnect, {});120 });121 afterEach(function() {122 mockSocketManager.teardown();123 socket = undefined;124 });125 it('Should send json',()=>{126 mockSocket().onopen();127 socket.send({'Hello Json World': 1});128 expect(mockSocket().send).toHaveBeenCalledWith('{"Hello Json World":1}\n');129 });130 it('Should recieve json',()=>{131 mockSocket().onopen();132 mockSocket().onmessage({data: '{"Hello Json World":2}\n'});133 expect(socket.onMessage).toHaveBeenCalledWith({'Hello Json World': 2});134 });135 it('Should split mutiple messages and call onMessage mutiple times', ()=>{136 mockSocket().onopen();137 mockSocket().onmessage({data: '{"a":1}\n{"b":2}\n'});138 expect(socket.onMessage.calls.argsFor(0)).toEqual([{a:1}]);139 expect(socket.onMessage.calls.argsFor(1)).toEqual([{b:2}]);140 });141});142describe('SubscriptionSocketReconnect', function() {143 const mockSocketManager = MockWebSocketManager();144 const mockSocket = ()=>mockSocketManager.getMockSocket();145 let socket;146 beforeEach(function() {147 socket = mockSocketManager.setup(SubscriptionSocketReconnect, {148 subscriptions: ['subscription1', 'subscription2'],149 });150 });151 afterEach(function() {152 mockSocketManager.teardown();153 socket = undefined;154 });155 it('Should subscribe on connect/reconnect',()=>{156 expect(mockSocket().send).not.toHaveBeenCalled();157 mockSocket().onopen();158 expect(mockSocket().send).toHaveBeenCalledWith(JSON.stringify({...

Full Screen

Full Screen

SocketController.test.js

Source:SocketController.test.js Github

copy

Full Screen

1import SocketController from 'module/SocketController';2let mockSocket;3let mockUser;4let mockState;5let mockRenderer;6let socketController;7beforeEach(() => {8 mockSocket = {};9 mockUser = {};10 mockState = {};11 mockRenderer = {};12 socketController = new SocketController(mockSocket, mockUser, mockState, mockRenderer);13});14it('should initialize the socket listener and listen and not show in scene', async () => {15 mockUser.viewedScene = 'not_a_viewed_scene';16 let socketOnArgs;17 mockSocket.on = jest.fn((...args) => {18 socketOnArgs = args;19 const data = {20 sceneId: 'a_scene_id',21 number: 1234,22 x: 1,23 y: 1,24 };25 // This is the callback function for `socket.on`. Let's call it to26 // validate what happens.27 args[1](data);28 });29 await socketController.init();30 mockRenderer.processNumericAndRender = jest.fn();31 expect(mockRenderer.processNumericAndRender).not.toHaveBeenCalled();32 expect(socketOnArgs[0]).toEqual('module.combat-numbers');33});34it('should listen and should show numeric type in scene', async () => {35 let socketOnArgs;36 const data = 1234;37 const x = 1;38 const y = 1;39 mockUser.viewedScene = 'a_scene_id';40 mockSocket.on = jest.fn((...args) => {41 socketOnArgs = args;42 const callbackData = {43 sceneId: 'a_scene_id',44 data,45 x,46 y,47 };48 // This is the callback function for `socket.on`. Let's call it to49 // validate what happens.50 args[1](callbackData);51 });52 mockRenderer.processNumericAndRender = jest.fn();53 await socketController.init();54 // Ensure that we are adding the combat number with the correct passing of55 // data.56 expect(mockRenderer.processNumericAndRender).toHaveBeenCalledTimes(1);57 expect(mockRenderer.processNumericAndRender).toHaveBeenCalledWith(data, x, y);58 expect(socketOnArgs[0]).toEqual('module.combat-numbers');59});60it('should listen and should show masked type in scene', async () => {61 let socketOnArgs;62 const data = 1234;63 const type = SocketController.emitTypes.TYPE_MASKED;64 const x = 1;65 const y = 1;66 mockUser.viewedScene = 'a_scene_id';67 mockSocket.on = jest.fn((...args) => {68 socketOnArgs = args;69 const callbackData = {70 sceneId: 'a_scene_id',71 data,72 type,73 x,74 y,75 };76 // This is the callback function for `socket.on`. Let's call it to77 // validate what happens.78 args[1](callbackData);79 });80 mockRenderer.processMaskedAndRender = jest.fn();81 await socketController.init();82 // Ensure that we are adding the combat number with the correct passing of83 // data.84 expect(mockRenderer.processMaskedAndRender).toHaveBeenCalledTimes(1);85 expect(mockRenderer.processMaskedAndRender).toHaveBeenCalledWith(data, x, y);86 expect(socketOnArgs[0]).toEqual('module.combat-numbers');87});88it('should deactivate the socket listener', async () => {89 mockSocket.off = jest.fn();90 await socketController.deactivate();91 expect(mockSocket.off).toHaveBeenCalledTimes(1);92 expect(mockSocket.off).toHaveBeenCalledWith('module.combat-numbers');93});94it('should not emit to socket if broadcasting is paused', async () => {95 mockState.getIsPauseBroadcast = () => true;96 mockSocket.on = jest.fn();97 mockSocket.emit = jest.fn();98 await socketController.init();99 await socketController.emit();100 expect(mockSocket.emit).not.toHaveBeenCalled();101});102it('should emit to socket', async () => {103 const data = 1234;104 const type = SocketController.emitTypes.TYPE_NUMERIC;105 const x = 1;106 const y = 1;107 const sceneId = 'a_scene_id';108 mockState.getIsPauseBroadcast = () => false;109 mockSocket.on = jest.fn();110 mockSocket.emit = jest.fn();111 await socketController.init();112 await socketController.emit(data, type, x, y, sceneId);113 const expectedPayload = [114 'module.combat-numbers',115 {116 data, type, x, y, sceneId,117 },118 ];119 expect(mockSocket.emit).toHaveBeenCalledWith(...expectedPayload);...

Full Screen

Full Screen

reactMiddlewareSpec.js

Source:reactMiddlewareSpec.js Github

copy

Full Screen

1const MemoryStream = require('memory-stream');2import { _testFunctions } from "../renderMiddleware";3import PageUtil from "../util/PageUtil";4import NullValuesPage from "./NullValuesPage";5import NullValuePromisesPage from "./NullValuePromisesPage";6import NormalValuesPage from "./NormalValuesPage";7describe("renderMiddleware", () => {8 let mockSocket,9 page;10 describe("null values", () => {11 beforeAll(() => {12 page = PageUtil.createPageChain([new NullValuesPage()]);13 });14 beforeEach(() => {15 mockSocket = new MemoryStream();16 });17 afterEach(() => {18 mockSocket = null;19 });20 it("don't render meta tags", (finishTest) => {21 _testFunctions.renderMetaTags(page, mockSocket)22 .then(() => {23 expect(mockSocket.toString()).toBe('');24 }, finishTest.fail)25 .done(finishTest);26 });27 it("don't render link tags", (finishTest) => {28 _testFunctions.renderLinkTags(page, mockSocket)29 .then(() => {30 expect(mockSocket.toString()).toBe('');31 }, finishTest.fail)32 .done(finishTest);33 });34 it("doesn't render base tag", (finishTest) => {35 _testFunctions.renderBaseTag(page, mockSocket)36 .then(() => {37 expect(mockSocket.toString()).toBe('');38 }, finishTest.fail)39 .done(finishTest);40 });41 });42 describe("promises with null values", () => {43 beforeAll(() => {44 page = PageUtil.createPageChain([new NullValuePromisesPage()]);45 });46 beforeEach(() => {47 mockSocket = new MemoryStream();48 });49 afterEach(() => {50 mockSocket = null;51 });52 it("don't render meta tags", (finishTest) => {53 _testFunctions.renderMetaTags(page, mockSocket)54 .then(() => {55 expect(mockSocket.toString()).toBe('');56 }, finishTest.fail)57 .done(finishTest);58 });59 it("don't render link tags", (finishTest) => {60 _testFunctions.renderLinkTags(page, mockSocket)61 .then(() => {62 expect(mockSocket.toString()).toBe('');63 }, finishTest.fail)64 .done(finishTest);65 });66 it("doesn't render base tag", (finishTest) => {67 _testFunctions.renderBaseTag(page, mockSocket)68 .then(() => {69 expect(mockSocket.toString()).toBe('');70 }, finishTest.fail)71 .done(finishTest);72 });73 });74 describe("good values", () => {75 beforeAll(() => {76 page = PageUtil.createPageChain([new NormalValuesPage()]);77 });78 beforeEach(() => {79 mockSocket = new MemoryStream();80 });81 afterEach(() => {82 mockSocket = null;83 });84 it("render a single meta tag", (finishTest) => {85 _testFunctions.renderMetaTags(page, mockSocket)86 .then(() => {87 expect(mockSocket.toString()).toBe('<meta charset="utf8">');88 }, finishTest.fail)89 .done(finishTest);90 });91 it("render a single link tags", (finishTest) => {92 _testFunctions.renderLinkTags(page, mockSocket)93 .then(() => {94 expect(mockSocket.toString()).toBe('<link data-react-server-link rel="prefetch" href="//www.google-analytics.com">');95 }, finishTest.fail)96 .done(finishTest);97 });98 it("render a base tag", (finishTest) => {99 _testFunctions.renderBaseTag(page, mockSocket)100 .then(() => {101 expect(mockSocket.toString()).toBe('<base href="//www.google.com">');102 }, finishTest.fail)103 .done(finishTest);104 });105 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var MockSocket = require('mock-socket').MockSocket;2var WebSocket = require('mock-socket').WebSocket;3var MockSocket = require('mock-socket').MockSocket;4var WebSocket = require('mock-socket').WebSocket;5var MockSocket = require('mock-socket').MockSocket;6var WebSocket = require('mock-socket').WebSocket;7var MockSocket = require('mock-socket').MockSocket;8var WebSocket = require('mock-socket').WebSocket;9var MockSocket = require('mock-socket').MockSocket;10var WebSocket = require('mock-socket').WebSocket;11var MockSocket = require('mock-socket').MockSocket;12var WebSocket = require('mock-socket').WebSocket;13var MockSocket = require('mock-socket').MockSocket;14var WebSocket = require('mock-socket').WebSocket;15var MockSocket = require('mock-socket').MockSocket;16var WebSocket = require('mock-socket').WebSocket;17var MockSocket = require('mock-socket').MockSocket;18var WebSocket = require('mock-socket').WebSocket;19var MockSocket = require('mock-socket').MockSocket;20var WebSocket = require('mock-socket').WebSocket;21var MockSocket = require('mock-socket').MockSocket;22var WebSocket = require('mock-socket').WebSocket;23var MockSocket = require('mock-socket').MockSocket;24var WebSocket = require('mock-socket').WebSocket;25var MockSocket = require('mock-socket').MockSocket;26var WebSocket = require('mock-socket').WebSocket;27var MockSocket = require('mock-socket').MockSocket;28var WebSocket = require('mock-socket').WebSocket;29var MockSocket = require('mock-socket').MockSocket;30var WebSocket = require('mock-socket').WebSocket

Full Screen

Using AI Code Generation

copy

Full Screen

1var MockSocket = require('mock-socket').MockSocket;2var io = require('socket.io-client');3});4var io = require('socket.io-client');5});6var io = require('socket.io-client');7});8var io = require('socket.io-client');9});10var io = require('socket.io-client');11});12var io = require('socket.io-client');13});14var io = require('socket.io-client');15});16var io = require('socket.io-client');

Full Screen

Using AI Code Generation

copy

Full Screen

1var MockSocket = require('mock-socket').WebSocket;2var MockSocket = require('mock-socket').WebSocket;3mockServer.on('message', function(data) {4 mockServer.send('Hello Client');5});6mockServer.on('close', function() {7 mockServer.send('Server closed');8});9socket.onmessage = function(event) {10 console.log(event.data);11};12socket.onclose = function(event) {13 if (event.wasClean) {14 alert('Connection closed cleanly');15 } else {16 alert('Connection died');17 }18 alert('Code: ' + event.code + ' reason: ' + event.reason);19};20socket.onerror = function(error) {21 alert("Error " + error.message);22};23socket.send('Hello Server');

Full Screen

Using AI Code Generation

copy

Full Screen

1var MockSocket = require('mock-socket').MockSocket;2socket.on('message', function(message) {3 console.log('received: ' + message);4});5socket.send('hello world');6socket.send('hello world2');7socket.send('hello world3');8socket.send('hello world4');9socket.send('hello world5');10socket.send('hello world6');11module.exports = function(config) {12 config.set({13 preprocessors: {14 },15 webpack: {16 module: {17 {18 }19 }20 },21 webpackMiddleware: {22 },23 coverageReporter: {24 {type: 'lcov', subdir: '.'}25 },26 require('karma-jasmine'),27 require('karma-chrome-launcher'),28 require('karma-webpack'),29 require('karma-coverage'),30 require('mock-socket')31 });32};

Full Screen

Using AI Code Generation

copy

Full Screen

1socket.on('connect', function() {2 console.log("connected");3 socket.emit('message', 'test');4});5socket.on('message', function(data) {6 console.log(data);7});8socket.on('disconnect', function() {9 console.log("disconnected");10});11module.exports = function(config) {12 config.set({13 { pattern: 'node_modules/socket.io-client/socket.io.js', included: false },14 { pattern: 'node_modules/socket.io-client/node_modules/socket.io-parser/index.js', included: false },15 { pattern: 'node_modules/socket.io-client/node_modules/socket.io-parser/is-buffer.js', included: false },16 { pattern: 'node_modules/socket.io-client/node_modules/component-emitter/index.js', included: false

Full Screen

Using AI Code Generation

copy

Full Screen

1var MockSocket = require('mock-socket').WebSocket;2ws.onopen = function() {3};4ws.onmessage = function(event) {5};6ws.send('something');7ws.close();

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 Karma 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