How to use startMockServer method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

hosts_bans.js

Source:hosts_bans.js Github

copy

Full Screen

...24}25describe('requests:hosts-bans', function () {26 this.timeout(5 * 1000)27 it('should timeout after the specified time', async () => {28 const { timeoutEndpoint } = await startMockServer()29 try {30 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)31 } catch (err) {32 rethrowShouldNotBeCalledErrors(err)33 err.type.should.equal('request-timeout')34 }35 })36 it('should not re-request a host that just had a timeout', async () => {37 const { timeoutEndpoint, host } = await startMockServer()38 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))39 try {40 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)41 } catch (err) {42 rethrowShouldNotBeCalledErrors(err)43 err.message.should.startWith('temporary ban')44 err.context.host.should.equal(host)45 const { banTime, expire } = err.context.hostBanData46 banTime.should.equal(baseBanTime)47 should(expire > Date.now()).be.true()48 should(expire < Date.now() + baseBanTime).be.true()49 }50 })51 it('should retry after expiration of the ban', async () => {52 const { timeoutEndpoint } = await startMockServer()53 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))54 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.message.should.startWith('temporary ban'))55 await wait(baseBanTime + 100)56 try {57 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)58 } catch (err) {59 rethrowShouldNotBeCalledErrors(err)60 err.type.should.equal('request-timeout')61 }62 })63 it('should keep timeout data for the whole host', async () => {64 const { timeoutEndpoint } = await startMockServer()65 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))66 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.message.should.startWith('temporary ban'))67 await wait(baseBanTime + 100)68 try {69 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)70 } catch (err) {71 rethrowShouldNotBeCalledErrors(err)72 err.type.should.equal('request-timeout')73 }74 })75 it('should increase ban time on next failure', async () => {76 const { timeoutEndpoint } = await startMockServer()77 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))78 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.message.should.startWith('temporary ban'))79 await wait(baseBanTime + 100)80 const beforeReban = Date.now()81 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))82 try {83 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)84 } catch (err) {85 rethrowShouldNotBeCalledErrors(err)86 err.message.should.startWith('temporary ban')87 const { banTime, expire } = err.context.hostBanData88 banTime.should.equal(baseBanTime * banTimeIncreaseFactor)89 const execTimeMargin = 100090 should(expire > beforeReban).be.true()91 should(expire < (beforeReban + baseBanTime * banTimeIncreaseFactor + execTimeMargin)).be.true()92 }93 })94 it('should reset ban time after a successful request', async () => {95 const { timeoutEndpoint, noTimeoutEndpoint } = await startMockServer()96 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))97 await wait(baseBanTime + 100)98 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))99 await wait(baseBanTime * banTimeIncreaseFactor + 100)100 await requests_.get(noTimeoutEndpoint, { timeout: 100 })101 const beforeReban = Date.now()102 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))103 try {104 await requests_.get(timeoutEndpoint, { timeout: 100 }).then(shouldNotBeCalled)105 } catch (err) {106 rethrowShouldNotBeCalledErrors(err)107 err.message.should.startWith('temporary ban')108 const { banTime, expire } = err.context.hostBanData109 banTime.should.equal(baseBanTime)110 const execTimeMargin = 1000111 should(expire > Date.now()).be.true()112 should(expire < (beforeReban + baseBanTime + execTimeMargin)).be.true()113 }114 })115 it('should count simultaneous requests failures as only one', async () => {116 const { timeoutEndpoint } = await startMockServer()117 await Promise.all([118 requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout')),119 requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => err.type.should.equal('request-timeout'))120 ])121 await requests_.get(timeoutEndpoint, { timeout: 100 }).catch(err => {122 const { banTime } = err.context.hostBanData123 banTime.should.equal(baseBanTime)124 })125 })126 it('should not re-request a host that just had a 500 error', async () => {127 const { errorEndpoint, noTimeoutEndpoint, host } = await startMockServer()128 await requests_.get(errorEndpoint)129 .then(shouldNotBeCalled)130 .catch(err => err.statusCode.should.equal(500))131 await hostIsCurrentlyBanned({ host, noTimeoutEndpoint })132 })133 it('should not re-request a host that just returned html rather than json', async () => {134 const { htmlEndpoint, noTimeoutEndpoint, host } = await startMockServer()135 await requests_.get(htmlEndpoint)136 .then(shouldNotBeCalled)137 .catch(err => {138 err.name.should.equal('SyntaxError')139 err.context.statusCode.should.equal(200)140 })141 await hostIsCurrentlyBanned({ host, noTimeoutEndpoint })142 })143})144const hostIsCurrentlyBanned = async ({ host, noTimeoutEndpoint }) => {145 try {146 await requests_.get(noTimeoutEndpoint).then(shouldNotBeCalled)147 } catch (err) {148 rethrowShouldNotBeCalledErrors(err)...

Full Screen

Full Screen

client.ts

Source:client.ts Github

copy

Full Screen

...29 mockServer?: Server;30 private app: Express;31 constructor() {32 super({33 // Gets populated in `startMockServer()`34 apiUrl: '',35 // Gets re-initialized for every test in `reset()`36 argv: [],37 authConfig: {},38 config: {},39 localConfig: {},40 stdin: new PassThrough(),41 stdout: new PassThrough(),42 stderr: new PassThrough(),43 output: new Output(new PassThrough()),44 });45 this.app = express();46 this.app.use(express.json());47 // play scenario48 this.app.use((req, res, next) => {49 this.scenario(req, res, next);50 });51 // catch requests that were not intercepted52 this.app.use((req, res) => {53 const message = `[Vercel API Mock] \`${req.method} ${req.path}\` was not handled.`;54 console.warn(message);55 res.status(404).json({56 error: {57 code: 'not_found',58 message,59 },60 });61 });62 this.scenario = Router();63 }64 reset() {65 this.stdin = new MockStream();66 this.stdout = new MockStream();67 this.stdout.setEncoding('utf8');68 this.stdout.end = () => {};69 this.stdout.pause();70 this.stderr = new MockStream();71 this.stderr.setEncoding('utf8');72 this.stderr.end = () => {};73 this.stderr.pause();74 this.stderr.isTTY = true;75 this._createPromptModule();76 this.output = new Output(this.stderr);77 this.argv = [];78 this.authConfig = {79 token: 'token_dummy',80 };81 this.config = {};82 this.localConfig = {};83 this.scenario = Router();84 }85 async startMockServer() {86 this.mockServer = createServer(this.app);87 await listen(this.mockServer, 0);88 const address = this.mockServer.address();89 if (!address || typeof address === 'string') {90 throw new Error('Unexpected http server address');91 }92 this.apiUrl = `http://127.0.0.1:${address.port}`;93 }94 stopMockServer() {95 return new Promise<void>((resolve, reject) => {96 if (!this.mockServer?.close) {97 reject(new Error(`mockServer did not exist when closing`));98 return;99 }100 this.mockServer.close(error => {101 if (error) {102 reject(error);103 return;104 }105 resolve();106 });107 });108 }109 setArgv(...argv: string[]) {110 this.argv = [process.execPath, 'cli.js', ...argv];111 }112 useScenario(scenario: Scenario) {113 this.scenario = scenario;114 }115}116export const client = new MockClient();117beforeAll(async () => {118 await client.startMockServer();119});120beforeEach(() => {121 client.reset();122});123afterAll(async () => {124 await client.stopMockServer();...

Full Screen

Full Screen

mockAPI.ts

Source:mockAPI.ts Github

copy

Full Screen

1import * as express from 'express';2import { createReadStream } from 'fs';3import { port } from '../../src/environments/e2e';4const mock = startMockServer(port);5function sendJSON(filePath: string) {6 return (req: express.Request, res: express.Response) => {7 res.setHeader('Access-Control-Allow-Origin', '*');8 res.setHeader(9 'Access-Control-Allow-Headers',10 'Origin, X-Requested-With, Content-Type, Accept'11 );12 res.setHeader('Content-Type', 'application/json');13 createReadStream(`${__dirname}/${filePath}`).pipe(res);14 };15}16function startMockServer(port: number) {17 const mock = express();18 // Our mocked API calls:19 mock.get('/', (req, res) =>20 res.status(200).json({ message: 'E2E mock server is alive.' })21 );22 mock.get(23 '/bitpay.com/api/rates/',24 sendJSON('mocks/bitpay.com_api_rates.json')25 );26 mock.get(27 '/bitpay.com/api/rates/bch',28 sendJSON('mocks/bitpay.com_api_rates_bch.json')29 );30 mock.listen(port, () =>...

Full Screen

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 pact-foundation-pact 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