Best JavaScript code snippet using pact-foundation-pact
matchers.ts
Source:matchers.ts
...288 }289 return value;290}291// Gets a matcher as JSON or the string value if it's not a matcher292export function matcherValueOrString(obj: unknown): string {293 if (typeof obj === 'string') return obj;294 return JSON.stringify(obj);...
pact.ts
Source:pact.ts
...95 }96 public withRequest(req: V3Request): PactV3 {97 if (req.body) {98 this.interaction.withRequestBody(99 matcherValueOrString(req.body),100 req.contentType ||101 contentTypeFromHeaders(req.headers, 'application/json')102 );103 }104 setRequestDetails(this.interaction, req);105 return this;106 }107 public withRequestBinaryFile(108 req: V3Request,109 contentType: string,110 file: string111 ): PactV3 {112 const body = readBinaryData(file);113 this.interaction.withRequestBinaryBody(body, contentType);114 setRequestDetails(this.interaction, req);115 return this;116 }117 public withRequestMultipartFileUpload(118 req: V3Request,119 contentType: string,120 file: string,121 mimePartName: string122 ): PactV3 {123 this.interaction.withRequestMultipartBody(contentType, file, mimePartName);124 setRequestDetails(this.interaction, req);125 return this;126 }127 public willRespondWith(res: V3Response): PactV3 {128 setResponseDetails(this.interaction, res);129 if (res.body) {130 this.interaction.withResponseBody(131 matcherValueOrString(res.body),132 res.contentType ||133 contentTypeFromHeaders(res.headers, 'application/json') // TODO: extract // force correct content-type header?134 );135 }136 this.states = [];137 return this;138 }139 public withResponseBinaryFile(140 res: V3Response,141 contentType: string,142 file: string143 ): PactV3 {144 const body = readBinaryData(file);145 this.interaction.withResponseBinaryBody(body, contentType);146 setResponseDetails(this.interaction, res);147 return this;148 }149 public withResponseMultipartFileUpload(150 res: V3Response,151 contentType: string,152 file: string,153 mimePartName: string154 ): PactV3 {155 this.interaction.withResponseMultipartBody(contentType, file, mimePartName);156 setResponseDetails(this.interaction, res);157 return this;158 }159 public async executeTest<T>(160 testFn: (mockServer: V3MockServer) => Promise<T>161 ): Promise<T | undefined> {162 const scheme = this.opts.tls ? 'https' : 'http';163 const host = this.opts.host || '127.0.0.1';164 const port = this.pact.createMockServer(165 host,166 this.opts.port,167 this.opts.tls168 );169 const server = { port, url: `${scheme}://${host}:${port}`, id: 'unknown' };170 let val: T | undefined;171 let error: Error | undefined;172 try {173 val = await testFn(server);174 } catch (e) {175 error = e;176 }177 const matchingResults = this.pact.mockServerMismatches(port);178 const errors = filterMissingFeatureFlag(matchingResults);179 const success = this.pact.mockServerMatchedSuccessfully(port);180 // Scenario: Pact validation failed181 if (!success && errors.length > 0) {182 let errorMessage = 'Test failed for the following reasons:';183 errorMessage += `\n\n ${generateMockServerError(matchingResults, '\t')}`;184 this.cleanup(false, server);185 // If the tests throws an error, we need to rethrow the error, but print out186 // any additional mock server errors to help the user understand what happened187 // (The proximate cause here is often the HTTP 500 from the mock server,188 // where the HTTP client then throws)189 if (error) {190 logger.error(errorMessage);191 throw error;192 }193 // Test didn't throw, so we need to ensure the test fails194 return Promise.reject(new Error(errorMessage));195 }196 // Scenario: test threw an error, but Pact validation was OK (error in client or test)197 if (error) {198 this.cleanup(false, server);199 throw error;200 }201 // Scenario: Pact validation passed, test didn't throw - return the callback value202 this.cleanup(true, server);203 return val;204 }205 private cleanup(success: boolean, server: V3MockServer) {206 if (success) {207 this.pact.writePactFile(this.opts.dir || './pacts');208 }209 this.pact.cleanupMockServer(server.port);210 this.setup();211 }212 // reset the internal state213 // (this.pact cannot be re-used between tests)214 private setup() {215 this.states = [];216 this.pact = makeConsumerPact(217 this.opts.consumer,218 this.opts.provider,219 this.opts.spec ?? SpecificationVersion.SPECIFICATION_VERSION_V3,220 this.opts.logLevel ?? 'info'221 );222 this.pact.addMetadata('pact-js', 'version', pactPackageVersion);223 }224}225const setRequestDetails = (226 interaction: ConsumerInteraction,227 req: V3Request228) => {229 interaction.withRequest(req.method, matcherValueOrString(req.path));230 forEachObjIndexed((v, k) => {231 interaction.withRequestHeader(k, 0, matcherValueOrString(v));232 }, req.headers);233 forEachObjIndexed((v, k) => {234 if (isArray(v)) {235 (v as unknown[]).forEach((vv, i) => {236 interaction.withQuery(k, i, matcherValueOrString(vv));237 });238 } else {239 interaction.withQuery(k, 0, matcherValueOrString(v));240 }241 }, req.query);242};243const setResponseDetails = (244 interaction: ConsumerInteraction,245 res: V3Response246) => {247 interaction.withStatus(res.status);248 forEachObjIndexed((v, k) => {249 interaction.withResponseHeader(k, 0, matcherValueOrString(v));250 }, res.headers);251};252const contentTypeFromHeaders = (253 headers: TemplateHeaders | undefined,254 defaultContentType: string255) => {256 let contentType: string | MatchersV3.Matcher<string> = defaultContentType;257 forEachObjIndexed((v, k) => {258 if (`${k}`.toLowerCase() === 'content-type') {259 contentType = matcherValueOrString(v);260 }261 }, headers || {});262 return contentType;...
ffi.ts
Source:ffi.ts
...22): string => {23 let contentType: string | Matcher<string> = defaultContentType;24 forEachObjIndexed((v, k) => {25 if (`${k}`.toLowerCase() === CONTENT_TYPE_HEADER) {26 contentType = matcherValueOrString(v);27 }28 }, headers || {});29 return contentType;30};31export const setRequestDetails = (32 interaction: ConsumerInteraction,33 req: RequestOptions34): void => {35 setRequestMethodAndPath(interaction, req);36 setBody(INTERACTION_PART.REQUEST, interaction, req.headers, req.body);37 setHeaders(INTERACTION_PART.REQUEST, interaction, req.headers);38 setQuery(interaction, req.query);39};40export const setResponseDetails = (41 interaction: ConsumerInteraction,42 res: ResponseOptions43): void => {44 interaction.withStatus(res.status);45 setBody(INTERACTION_PART.RESPONSE, interaction, res.headers, res.body);46 setHeaders(INTERACTION_PART.RESPONSE, interaction, res.headers);47};48export const setRequestMethodAndPath = (49 interaction: ConsumerInteraction,50 req: RequestOptions51): void => {52 if (req?.method && req?.path) {53 const method = req?.method;54 const reqPath = matcherValueOrString(req?.path);55 interaction.withRequest(method, reqPath);56 }57};58export const setQuery = (59 interaction: ConsumerInteraction,60 query?: Query61): void => {62 forEachObjIndexed((v, k) => {63 if (isArray(v)) {64 (v as unknown[]).forEach((vv, i) => {65 interaction.withQuery(k, i, matcherValueOrString(vv));66 });67 } else {68 interaction.withQuery(k, 0, matcherValueOrString(v));69 }70 }, query);71};72export const setBody = (73 part: INTERACTION_PART,74 interaction: ConsumerInteraction,75 headers?: Headers,76 body?: AnyTemplate77): void => {78 if (body) {79 const matcher = matcherValueOrString(body);80 const contentType = contentTypeFromHeaders(headers, CONTENT_TYPE_JSON);81 switch (part) {82 case INTERACTION_PART.REQUEST:83 interaction.withRequestBody(matcher, contentType);84 break;85 case INTERACTION_PART.RESPONSE:86 interaction.withResponseBody(matcher, contentType);87 break;88 default:89 break;90 }91 }92};93export const setHeaders = (94 part: INTERACTION_PART,95 interaction: ConsumerInteraction,96 headers?: Headers97): void => {98 forEachObjIndexed((v, k) => {99 switch (part) {100 case INTERACTION_PART.REQUEST:101 interaction.withRequestHeader(`${k}`, 0, matcherValueOrString(v));102 break;103 case INTERACTION_PART.RESPONSE:104 interaction.withResponseHeader(`${k}`, 0, matcherValueOrString(v));105 break;106 default:107 break;108 }109 }, headers);...
Using AI Code Generation
1var matcherValueOrString = require('pact-foundation-pact-node').matchers;2var chai = require('chai');3var chaiAsPromised = require('chai-as-promised');4chai.use(chaiAsPromised);5var expect = chai.expect;6var provider = require('./provider');7var request = require('superagent');8describe("Pact with NodeJS", function() {9 describe("GET /", function() {10 it("should return a list of all users", function(done) {11 provider.addInteraction({12 withRequest: {13 },14 willRespondWith: {15 headers: {16 'Content-Type': 'application/json; charset=utf-8'17 },18 body: {19 users: matcherValueOrString.eachLike({20 name: matcherValueOrString.string("Bob"),21 age: matcherValueOrString.integer(42)22 }, 1)23 }24 }25 }).then(function() {26 return request.get(URL).end();27 }).then(function(response) {28 expect(response.status).to.equal(200);29 expect(response.body.users).to.have.length(1);30 expect(response.body.users[0].name).to.equal("Bob");31 expect(response.body.users[0].age).to.equal(42);32 }).then(done, done);33 });34 });35});
Using AI Code Generation
1const pact = require('pact-foundation/pact');2const { matcherValueOrString } = pact.Matchers;3const { somethingLike, like, term, eachLike, eachLikeWithMin } = pact.Matchers;4const { like: like2, term: term2, eachLike: eachLike2, eachLikeWithMin: eachLikeWithMin2 } = pact.Matchers;5const { like: like3, term: term3, eachLike: eachLike3, eachLikeWithMin: eachLikeWithMin3 } = pact.Matchers;6const { like: like4, term: term4, eachLike: eachLike4, eachLikeWithMin: eachLikeWithMin4 } = pact.Matchers;7const { like: like5, term: term5, eachLike: eachLike5, eachLikeWithMin: eachLikeWithMin5 } = pact.Matchers;8const { like: like6, term: term6, eachLike: eachLike6, eachLikeWithMin: eachLikeWithMin6 } = pact.Matchers;9const { like: like7, term: term7, eachLike: eachLike7, eachLikeWithMin: eachLikeWithMin7 } = pact.Matchers;10const { like: like8, term: term8, eachLike: eachLike8, eachLikeWithMin: eachLikeWithMin8 } = pact.Matchers;11const { like: like9, term: term9, eachLike: eachLike9, eachLikeWithMin: eachLikeWithMin9 } = pact.Matchers;12const { like: like10, term: term10, eachLike: eachLike10, eachLikeWithMin: eachLikeWithMin10 } = pact.Matchers;13const { like: like11, term: term11, eachLike: eachLike11, eachLikeWithMin: eachLikeWithMin11 } = pact.Matchers;14const { like: like12, term: term12, eachLike: eachLike12, eachLikeWithMin: eachLikeWithMin12 } = pact.Matchers;15const { like: like13, term: term13, eachLike: eachLike13, eachLikeWithMin: eachLikeWithMin13 } = pact.Matchers;16const { like: like14, term: term14, eachLike: eachLike14, eachLikeWithMin: eachLikeWithMin14 } = pact.Matchers;17const { like: like15, term: term15,
Using AI Code Generation
1const { Matchers } = require('@pact-foundation/pact')2const { matcherValueOrString } = Matchers3const response = {4 name: matcherValueOrString('Hello', 'Hello')5}6console.log(response)7{8 "name": {9 "data": {10 "matcher": {11 }12 }13 }14}15matcherLike ( value [, options ] )16matcherTerm ( options )17const { Matchers } = require('@pact-foundation/pact')18const { matcherTerm } = Matchers
Using AI Code Generation
1var matcherValueOrString = require('./index.js').matcherValueOrString;2var matchers = {3 body: {4 name: matcherValueOrString("Joe"),5 age: matcherValueOrString(42)6 }7};8console.log(matchers);9{ body: { name: { match: 'Joe' }, age: { match: 42 } } }10Copyright (c) 2019 Pact Foundation11Licensed under the Apache License, Version 2.0 (the "License");
Using AI Code Generation
1const pactNode = require("pact-foundation-pact-node");2const matcherValueOrString = pactNode.matcherValueOrString;3const matcher = matcherValueOrString("test", "term");4console.log(matcher);5import { matcherValueOrString } from "pact-foundation-pact-web";6const matcher = matcherValueOrString("test", "term");7console.log(matcher);8import { matcherValueOrString } from "pact-foundation-pact-web";9const matcher = matcherValueOrString("test", "term");10console.log(matcher);
Using AI Code Generation
1const pact = require('pact-foundation-pact-node');2const { matcherValueOrString } = pact.Matchers;3const { somethingLike } = pact.Matchers;4const expectedBody = {5 name: matcherValueOrString('John'),6 age: somethingLike(20),7 address: {8 line1: somethingLike('line1'),9 line2: somethingLike('line2'),10 line3: somethingLike('line3'),11 },12};13console.log(expectedBody);14const expectedBody = {15 name: matcherValueOrString('John'),16 age: somethingLike(20),17 address: {18 line1: somethingLike('line1'),19 line2: somethingLike('line2'),20 line3: somethingLike('line3'),21 },22};23console.log(expectedBody);24const expectedBody = {25 name: matcherValueOrString('John'),26 age: somethingLike(20),27 address: {28 line1: somethingLike('line1'),29 line2: somethingLike('line2'),30 line3: somethingLike('line3'),31 },32};33console.log(expectedBody);34const expectedBody = {35 name: matcherValueOrString('John'),36 age: somethingLike(20),37 address: {38 line1: somethingLike('line1'),39 line2: somethingLike('
Using AI Code Generation
1const {matcherValueOrString} = require('@pact-foundation/pact-node');2const matcher = matcherValueOrString(10, '10');3console.log(matcher);4const matcher2 = matcherValueOrString('10', '10');5console.log(matcher2);6const matcher3 = matcherValueOrString(10, '1');7console.log(matcher3);8const matcher4 = matcherValueOrString(10, '0');9console.log(matcher4);10const matcher5 = matcherValueOrString(10, 'a');11console.log(matcher5);12const matcher6 = matcherValueOrString(10, 'A');13console.log(matcher6);14const matcher7 = matcherValueOrString(10, 'z');15console.log(matcher7);
Using AI Code Generation
1const pact = require('pact-foundation/pact-node');2const matcher = require('pact-foundation/pact-node/matchers');3const matcherValue = matcher.somethingLike('test');4const value = pact.matcherValueOrString(matcherValue);5console.log(value);6{ json_class: 'Pact::Term',7 data: { gen
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!!