Best JavaScript code snippet using pact-foundation-pact
net.spec.ts
Source:net.spec.ts
1import chai from 'chai';2import chaiAsPromised from 'chai-as-promised';3import nodeNet from 'net';4import { isPortAvailable } from './net';5import logger from './logger';6const { expect } = chai;7chai.use(chaiAsPromised);8describe('Net', () => {9 const port = 4567;10 const defaultHost = '0.0.0.0';11 const specialPort = process.platform.match('win') ? -1 : 80;12 // Utility function to create a server on a given port and return a Promise13 const createServer = (p: number, host = defaultHost) =>14 new Promise((resolve, reject) => {15 const server = nodeNet.createServer();16 server.on('error', (err: any) => reject(err));17 server.on('listening', () => resolve(server));18 server.listen({ port: p, host, exclusive: true }, () => {19 logger.info(`test server is up on ${host}:${p}`);20 });21 });22 describe('#isPortAvailable', () => {23 context('when the port is not allowed to be bound', () => {24 it('returns a rejected promise', () =>25 expect(isPortAvailable(specialPort, defaultHost)).to.eventually.be26 .rejected);27 });28 context('when the port is available', () => {29 it('returns a fulfilled promise', () =>30 expect(isPortAvailable(port, defaultHost)).to.eventually.be.fulfilled);31 });32 context('when the port is unavailable', () => {33 let closeFn = (cb: any) => cb();34 it('returns a rejected promise', () =>35 createServer(port).then((server: { close(): any }) => {36 closeFn = server.close.bind(server);37 return expect(isPortAvailable(port, defaultHost)).to.eventually.be38 .rejected;39 }));40 // close the servers used in this test as to not conflict with other tests41 afterEach((done) => closeFn(done));42 });43 context('when a single host is unavailable', () => {44 let closeFn = (cb: any) => cb();45 it('returns a fulfilled promise', () =>46 // simulate ::1 being unavailable47 createServer(port, '::1').then((server: { close(): any }) => {48 closeFn = server.close.bind(server);49 // this should work as the `127.0.0.1` is NOT `::1`50 return expect(isPortAvailable(port, '127.0.0.1')).to.eventually.be51 .fulfilled;52 }));53 // close the servers used in this test as to not conflict with other tests54 afterEach((done) => closeFn(done));55 });56 });...
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!!