Best JavaScript code snippet using pact-foundation-pact
index.spec.ts
Source: index.spec.ts
1// @ts-nocheck2import chai from 'chai';3import chaiAsPromised from 'chai-as-promised';4import sinon from 'sinon';5import sinonChai from 'sinon-chai';6import { PactOptions, PactOptionsComplete } from '../dsl/options';7import { Pact } from '.';8import { ConsumerInteraction, ConsumerPact } from '@pact-foundation/pact-core';9chai.use(sinonChai);10chai.use(chaiAsPromised);11const { expect } = chai;12describe('Pact', () => {13 const fullOpts = {14 consumer: 'A',15 provider: 'B',16 port: 1234,17 host: '127.0.0.1',18 ssl: false,19 logLevel: 'info',20 spec: 2,21 cors: false,22 pactfileWriteMode: 'merge',23 } as PactOptionsComplete;24 afterEach(() => {25 sinon.restore();26 });27 describe('#constructor', () => {28 it('throws Error when consumer not provided', () => {29 expect(() => {30 new Pact({ consumer: '', provider: 'provider' });31 }).to.throw(Error, 'You must specify a Consumer for this pact.');32 });33 it('throws Error when provider not provided', () => {34 expect(() => {35 new Pact({ consumer: 'someconsumer', provider: '' });36 }).to.throw(Error, 'You must specify a Provider for this pact.');37 });38 });39 describe('#createOptionsWithDefault', () => {40 const constructorOpts: PactOptions = {41 consumer: 'A',42 provider: 'B',43 };44 it('merges options with sensible defaults', () => {45 const opts = Pact.createOptionsWithDefaults(constructorOpts);46 expect(opts.consumer).to.eq('A');47 expect(opts.provider).to.eq('B');48 expect(opts.cors).to.eq(false);49 expect(opts.host).to.eq('127.0.0.1');50 expect(opts.logLevel).to.eq('info');51 expect(opts.spec).to.eq(2);52 expect(opts.dir).not.to.be.empty;53 expect(opts.log).not.to.be.empty;54 expect(opts.pactfileWriteMode).to.eq('merge');55 expect(opts.ssl).to.eq(false);56 expect(opts.sslcert).to.eq(undefined);57 expect(opts.sslkey).to.eq(undefined);58 });59 });60 describe('#setup', () => {61 describe('when server is properly configured', () => {62 it('updates the mock service configuration', async () => {63 const p: Pact = new Pact(fullOpts);64 await p.setup();65 expect(p.mockService).to.deep.equal({66 baseUrl: 'http://127.0.0.1:1234',67 pactDetails: {68 pactfile_write_mode: 'merge',69 consumer: {70 name: 'A',71 },72 provider: { name: 'B' },73 },74 });75 });76 it('returns the current configuration', () => {77 const p: any = new Pact(fullOpts);78 return expect(p.setup()).to.eventually.include({79 consumer: 'A',80 provider: 'B',81 port: 1234,82 host: '127.0.0.1',83 ssl: false,84 logLevel: 'info',85 spec: 2,86 cors: false,87 pactfileWriteMode: 'merge',88 });89 });90 });91 describe('when a port is given', () => {92 it('checks if the port is available', () => {93 const p: any = new Pact(fullOpts);94 return expect(p.setup())95 .to.eventually.have.property('port')96 .eq(fullOpts.port);97 });98 });99 describe('when no port is given', () => {100 it('finds a free port', () => {101 const opts = {102 ...fullOpts,103 port: undefined,104 };105 const p: any = new Pact(opts);106 return expect(p.setup()).to.eventually.have.property('port').not107 .undefined;108 });109 });110 });111 describe('#addInteraction', () => {112 // This is more of an integration test, as the function has taken on a lot more113 // responsibility previously covered by other functions during the upgrade to114 // the rust core, to ensure the API remains backwards compatible115 it('sets the correct request and response details on the FFI and starts the mock server', () => {116 const p: Pact = new Pact(fullOpts);117 const uponReceiving = sinon.stub().returns(true);118 const given = sinon.stub().returns(true);119 const withRequest = sinon.stub().returns(true);120 const withRequestBody = sinon.stub().returns(true);121 const withRequestHeader = sinon.stub().returns(true);122 const withQuery = sinon.stub().returns(true);123 const withResponseBody = sinon.stub().returns(true);124 const withResponseHeader = sinon.stub().returns(true);125 const withStatus = sinon.stub().returns(true);126 const createMockServer = sinon.stub().returns(1234);127 const pactMock: ConsumerPact = {128 createMockServer,129 };130 const interactionMock: ConsumerInteraction = {131 uponReceiving,132 given,133 withRequest,134 withRequestBody,135 withRequestHeader,136 withQuery,137 withResponseBody,138 withResponseHeader,139 withStatus,140 };141 p.pact = pactMock;142 p.interaction = interactionMock;143 p.mockService = {};144 p.addInteraction({145 state: 'some state',146 uponReceiving: 'some description',147 withRequest: {148 method: 'GET',149 path: '/',150 body: { foo: 'bar' },151 headers: {152 'content-type': 'application/json',153 foo: 'bar',154 },155 query: {156 query: 'string',157 foo: 'bar',158 },159 },160 willRespondWith: {161 status: 200,162 body: { baz: 'bat' },163 headers: {164 'content-type': 'application/hal+json',165 foo: 'bar',166 },167 },168 });169 expect(uponReceiving.calledOnce).to.be.true;170 expect(given.calledOnce).to.be.true;171 expect(withRequest.calledOnce).to.be.true;172 expect(withQuery.calledTwice).to.be.true;173 expect(withRequestHeader.calledTwice).to.be.true;174 expect(withRequestBody.calledOnce).to.be.true;175 expect(withResponseBody.calledOnce).to.be.true;176 expect(withResponseHeader.calledTwice).to.be.true;177 // Pact mock server started178 expect(createMockServer.called).to.be.true;179 });180 });...
expectation-builder.spec.js
Source: expectation-builder.spec.js
...39 expect(builder.expectation.responseBody).toBe('some resp body');40 });41 it('sends a headers', () => {42 expect(builder.expectation.responseHeaders).toEqual({});43 builder.withResponseHeader('h1', 'v1');44 expect(builder.expectation.responseHeaders).toEqual({'h1': 'v1'});45 builder.withResponseHeader('h2', 'v2');46 expect(builder.expectation.responseHeaders).toEqual({'h1': 'v1', 'h2': 'v2'});47 });...
serverCall.js
Source: serverCall.js
1import axios from "axios";2export const axiosInstance = axios.create({3 baseURL: "https://api.openweathermap.org",4 headers: {5 Origin: "*",6 Accept: "application/json",7 "Content-Type": "application/json",8 },9});10const serverRequest = (method = "POST") => (url) => async (11 data,12 options = {13 params: {},14 withResponseHeader: false,15 withResponseComplete: false,16 }17) => {18 const query = {19 method,20 url,21 data,22 };23 if (options.params) {24 query.params = options.params;25 }26 let extras = {};27 28 if (options.contentType) {29 extras.contentType = options.contentType || "application/json";30 }31 try {32 let result = await axiosInstance(query);33 if (options.withResponseComplete) {34 return result;35 }36 if (options.withResponseHeader) {37 return {38 headers: {39 ...result.headers,40 status: result.status,41 },42 ...result.data,43 };44 }45 return result.data;46 } catch (error) {47 throw error.response;48 }49};50export const getRequest = serverRequest("GET");51export const postRequest = serverRequest("POST");52export const putRequest = serverRequest("PUT");53export const deleteRequest = serverRequest("DELETE");...
Check out the latest blogs from LambdaTest on this topic:
Hey everyone! We hope you had a great Hacktober. At LambdaTest, we thrive to bring you the best with each update. Our engineering and tech teams work at lightning speed to deliver you a seamless testing experience.
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
In today’s world, an organization’s most valuable resource is its customers. However, acquiring new customers in an increasingly competitive marketplace can be challenging while maintaining a strong bond with existing clients. Implementing a customer relationship management (CRM) system will allow your organization to keep track of important customer information. This will enable you to market your services and products to these customers better.
When I started writing tests with Cypress, I was always going to use the user interface to interact and change the application’s state when running tests.
Sometimes, in our test code, we need to handle actions that apparently could not be done automatically. For example, some mouse actions such as context click, double click, drag and drop, mouse movements, and some special key down and key up actions. These specific actions could be crucial depending on the project context.
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!!