Best JavaScript code snippet using pact-foundation-pact
verifier.spec.ts
Source:verifier.spec.ts
1/* tslint:disable:no-unused-expression no-empty no-string-literal*/2import * as chai from "chai"3import * as chaiAsPromised from "chai-as-promised"4import * as sinon from "sinon"5import { Verifier, VerifierOptions } from "./verifier"6import serviceFactory from "@pact-foundation/pact-node"7import logger from "../common/logger"8import * as http from "http"9import * as express from "express"10chai.use(chaiAsPromised)11const expect = chai.expect12describe("Verifier", () => {13 afterEach(() => {14 sinon.restore()15 })16 const state = "thing exists"17 let v: Verifier18 let opts: VerifierOptions19 let executed: boolean20 const providerBaseUrl = "http://not.exists"21 // Little function to mock out an Event Emitter22 const fakeServer = (event: string) => ({23 on: (registeredEvent: string, cb: any) => {24 if (registeredEvent === event) {25 cb()26 }27 },28 })29 beforeEach(() => {30 executed = false31 opts = {32 providerBaseUrl,33 requestFilter: (req, res, next) => {34 next()35 },36 stateHandlers: {37 [state]: () => {38 executed = true39 return Promise.resolve("done")40 },41 },42 }43 })44 describe("#constructor", () => {45 describe("when given configuration", () => {46 it("sets the configuration on the object", () => {47 v = new Verifier(opts)48 expect(v)49 .to.have.deep.property("config")50 .includes({51 providerBaseUrl,52 })53 expect(v).to.have.nested.property("config.stateHandlers")54 expect(v).to.have.nested.property("config.requestFilter")55 })56 })57 describe("when no configuration is given", () => {58 it("does not set the configuration on the object", () => {59 v = new Verifier()60 expect(v).to.not.have.deep.property("config")61 })62 })63 })64 describe("#setConfig", () => {65 let spy: sinon.SinonSpy66 beforeEach(() => {67 spy = sinon.spy(serviceFactory, "logLevel")68 v = new Verifier(opts)69 })70 context("when logLevel is provided", () => {71 it("sets the log level on pact node", () => {72 v["setConfig"]({73 ...opts,74 logLevel: "debug",75 })76 expect(spy.callCount).to.eql(1)77 })78 })79 context("when logLevel is not provided", () => {80 it("does not modify the log setting", () => {81 v["setConfig"]({82 ...opts,83 })84 expect(spy.callCount).to.eql(0)85 })86 })87 context("when a deprecated field is provided", () => {88 it("logs a warning", () => {89 spy = sinon.spy(logger, "warn")90 v["setConfig"]({91 ...opts,92 providerStatesSetupUrl: "http://foo.com",93 })94 expect(spy.callCount).to.eql(1)95 })96 })97 })98 describe("#setupStates", () => {99 describe("when there are provider states on the pact", () => {100 describe("and there are handlers associated with those states", () => {101 it("executes the handler and returns a set of Promises", async () => {102 v = new Verifier(opts)103 const res = await v["setupStates"]({104 states: [state],105 })106 expect(res).lengthOf(1)107 expect(executed).to.be.true108 })109 })110 describe("and there are no handlers associated with those states", () => {111 it("executes the handler and returns an empty Promise", async () => {112 const spy = sinon.spy(logger, "warn")113 delete opts.stateHandlers114 v = new Verifier(opts)115 const res = await v["setupStates"]({116 states: [state],117 })118 expect(res).lengthOf(0)119 expect(spy.callCount).to.eql(1)120 expect(executed).to.be.false121 })122 })123 })124 describe("when there are no provider states on the pact", () => {125 it("executes the handler and returns an empty Promise", async () => {126 v = new Verifier(opts)127 const res = await v["setupStates"]({})128 expect(res).lengthOf(0)129 })130 })131 })132 describe("#verifyProvider", () => {133 beforeEach(() => {134 v = new Verifier()135 sinon.stub(v, "startProxy" as any).returns({136 close: () => {137 executed = true138 },139 })140 sinon.stub(v, "waitForServerReady" as any).returns(Promise.resolve())141 })142 describe("when no configuration has been given", () => {143 it("fails with an error", () => {144 return expect(v.verifyProvider()).to.eventually.be.rejectedWith(Error)145 })146 })147 describe("when the verifier has been configured", () => {148 context("and the verification runs successfully", () => {149 it("closes the server and returns the result", () => {150 sinon151 .stub(v, "runProviderVerification" as any)152 .returns(Promise.resolve("done"))153 const res = v.verifyProvider(opts)154 return expect(res).to.eventually.be.fulfilled.then(() => {155 expect(executed).to.be.true156 })157 })158 })159 context("and the verification fails", () => {160 it("closes the server and returns the result", () => {161 sinon162 .stub(v, "runProviderVerification" as any)163 .returns(() => Promise.reject("error"))164 const res = v.verifyProvider(opts)165 return expect(res).to.eventually.be.rejected.then(() => {166 expect(executed).to.be.true167 })168 })169 })170 })171 })172 describe("#waitForServerReady", () => {173 beforeEach(() => {174 v = new Verifier()175 })176 context("when the server starts successfully", () => {177 it("returns a successful promise", () => {178 const res = v["waitForServerReady"](fakeServer(179 "listening"180 ) as http.Server)181 return expect(res).to.eventually.be.fulfilled182 })183 })184 context("when the server fails to start", () => {185 it("returns an error", () => {186 const res = v["waitForServerReady"](fakeServer("error") as http.Server)187 return expect(res).to.eventually.be.rejected188 })189 })190 })191 describe("#createProxyStateHandler", () => {192 v = new Verifier()193 let res: any194 const mockResponse = {195 sendStatus: (status: number) => {196 res = status197 },198 status: (status: number) => {199 res = status200 return {201 send: () => {},202 }203 },204 }205 context("when valid state handlers are provided", () => {206 it("returns a 200", () => {207 sinon.stub(v, "setupStates" as any).returns(Promise.resolve())208 const h = v["createProxyStateHandler"]()209 return expect(h({}, mockResponse)).to.eventually.be.fulfilled.then(210 () => {211 expect(res).to.eql(200)212 }213 )214 })215 })216 context("when there is a problem with a state handler", () => {217 it("returns a 500", () => {218 sinon219 .stub(v, "setupStates" as any)220 .returns(Promise.reject("state error"))221 const h = v["createProxyStateHandler"]()222 return expect(h({}, mockResponse)).to.eventually.be.fulfilled.then(223 () => {224 expect(res).to.eql(500)225 }226 )227 })228 })229 })230 describe("#startProxy", () => {231 v = new Verifier()232 it("starts a given http.Server", () => {233 v["startProxy"](express())234 })235 })...
messageProviderPact.spec.ts
Source:messageProviderPact.spec.ts
...131 describe("when the http server starts up", () => {132 it("returns a resolved promise", () => {133 const waitForServerReady = (provider as any).waitForServerReady134 const server = http.createServer(() => {}).listen()135 return expect(waitForServerReady(server)).to.eventually.be.fulfilled136 })137 })138 })139 describe("#setupProxyServer", () => {140 describe("when the http server starts up", () => {141 it("returns a resolved promise", () => {142 const setupProxyServer = (provider as any).setupProxyServer143 const app = express()144 expect(setupProxyServer(app)).to.be.an.instanceOf(http.Server)145 })146 })147 })148 describe("#setupProxyApplication", () => {149 it("returns a valid express app", () => {...
APIClient.ts
Source:APIClient.ts
...19 }20 // its 2018, most of the market supports sockets + ajax requests can struggle behind load balancers21 this.socket = io(this.serverAddress, {transports: ['websocket']});22 this.registerSocketEvents();23 await this.waitForServerReady();24 }25 // TODO: Test disconnections / reconnection26 private registerSocketEvents() {27 this.socket.on('disconnect', () => {28 // mark all endpoint clients as disconnected29 // this is because when the socket disconnects the server automatically garbage collects all endpoints30 // even if we come online, these will no longer work31 this.connectedEndpoints.forEach(endpoint => {32 endpoint.isDisconnected = true;33 });34 this.connectedEndpoints = [];35 this.emit('disconnect');36 });37 this.socket.on('reconnect', () => {38 this.waitForServerReady()39 .then(() => {40 // connected back to the server, ready to go41 this.emit('reconnect');42 })43 .catch(console.error);44 });45 }46 async waitForServerReady() {47 return new Promise((resolve, reject) => {48 const serverReadyTimer = setTimeout(() => {49 reject(new ConnectionTimeoutError('Timed out waiting for serverReady'));50 }, this.timeout);51 this.socket.on('serverReady', () => {52 clearTimeout(serverReadyTimer);53 resolve();54 });55 });56 }57 //Used for unit tests58 async mockSocketConnect(mockSocket: IBasicSocket) {59 this.socket = mockSocket;60 await this.waitForServerReady();61 }62 public async connectToEndpoint(endpointName: string, accessKey?: string): Promise<APIEndpointClient> {63 if (!this.socket) {64 throw new Error('Cannot connect to endpoint before socket connection is established, have you forgotten to call connect() ?');65 }66 if (!accessKey && this.accessKey) {67 accessKey = this.accessKey; //Use connection level default accessKey68 }69 return new Promise<APIEndpointClient>((resolve, reject) => {70 let hasTimedOut = false;71 const timeoutTimer = setTimeout(() => {72 hasTimedOut = true;73 reject(new ConnectionTimeoutError(`connectToEndpoint('${endpointName}') timed out`));74 }, this.timeout);...
Using AI Code Generation
1const {Pact} = require('@pact-foundation/pact');2const {waitForServerReady} = require('@pact-foundation/pact-mock-service');3const port = 1234;4const provider = new Pact({5});6waitForServerReady(port, 'localhost').then(() => {7});
Using AI Code Generation
1var pact = require('pact-foundation/pact-web');2 console.log('Pact server ready');3});4var pact = require('pact-foundation/pact-node');5 console.log('Pact server ready');6});7var pact = require('pact-foundation/pact-web');8 console.log('Pact server ready');9});
Using AI Code Generation
1var pact = require('pact-foundation/pact-node');2}).catch(function (err) {3});4var pact = require('pact-node');5}).catch(function (err) {6});7var pact = require('pact-node');8var opts = {9};10pact.server(opts).then(function (server) {11 server.start();12 }).catch(function (err) {13 });14});
Using AI Code Generation
1var pact = require('pact-foundation/pact-node');2var path = require('path');3var server = pact.createServer({4 log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),5 dir: path.resolve(process.cwd(), 'pacts'),6});7server.start()8 .then(function() {9 return pact.waitForServerReady(1234, 10000);10 })11 .then(function() {12 return server.stop();13 })14 .catch(function(e) {15 console.log(e);16 });17var pact = require('pact-foundation/pact-node');18var path = require('path');19var server = pact.createServer({20 log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),21 dir: path.resolve(process.cwd(), 'pacts'),22});23server.start()24 .then(function() {25 return pact.waitForServerReady(1234, 10000);26 })27 .then(function() {28 return server.stop();29 })30 .catch(function(e) {31 console.log(e);32 });33var pact = require('pact-foundation/pact-node');34var path = require('path');35var server = pact.createServer({36 log: path.resolve(process.cwd(), 'logs', 'mockserver-integration.log'),37 dir: path.resolve(process.cwd(), 'pacts'),38});39server.start()40 .then(function() {41 return pact.waitForServerReady(1234, 10000);42 })43 .then(function() {44 return server.stop();45 })
Using AI Code Generation
1const Pact = require('@pact-foundation/pact-node');2const request = require('superagent');3const expect = require('chai').expect;4const PORT = 1234;5describe('Pact', () => {6 let server;7 before(() => {8 server = require('./server');9 server.listen(PORT);10 });11 after(() => {12 server.close();13 });14 describe('Test GET /test', () => {15 it('should return 200', () => {16 const url = `${HOST}:${PORT}/test`;17 return Pact.waitForServerReady(PORT, HOST).then(() => {18 .get(url)19 .then(res => {20 expect(res.status).to.be.equals(200);21 });22 });23 });24 });25});26const express = require('express');27const app = express();28app.get('/test', (req, res) => {29 res.send('Hello World!');30});31module.exports = app;
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!