Best JavaScript code snippet using pact-foundation-pact
matchers.spec.ts
Source:matchers.spec.ts
...118 });119 describe('#atMostLike', () => {120 describe('with no examples', () => {121 it('returns a JSON representation of an atMostLike matcher', () => {122 const result = MatchersV3.atMostLike(123 {124 a: 'b',125 },126 2127 );128 expect(result).to.deep.equal({129 'pact:matcher:type': 'type',130 max: 2,131 value: [{ a: 'b' }],132 });133 });134 });135 describe('when provided examples', () => {136 it('returns a JSON representation of an atMostLike matcher with the correct number of examples', () => {137 const result = MatchersV3.atMostLike(138 {139 a: 'b',140 },141 4,142 4143 );144 expect(result).to.deep.equal({145 'pact:matcher:type': 'type',146 max: 4,147 value: [{ a: 'b' }, { a: 'b' }, { a: 'b' }, { a: 'b' }],148 });149 });150 });151 it('throws an error if the number of examples is more than the maximum', () => {152 expect(() => MatchersV3.atMostLike({ a: 'b' }, 2, 4)).to.throw(153 'atMostLike has a maximum of 2 but 4 elements where requested. Make sure the count is less than or equal to the max.'154 );155 });156 });157 describe('#constrainedArrayLike', () => {158 describe('with no examples', () => {159 it('returns a JSON representation of an constrainedArrayLike matcher', () => {160 const result = MatchersV3.constrainedArrayLike(161 {162 a: 'b',163 },164 2,165 4166 );...
matchers.ts
Source:matchers.ts
1import { isNil, pickBy, times } from 'ramda';2import RandExp from 'randexp';3import { AnyJson, JsonMap } from '../common/jsonTypes';4/**5 * Pact Matcher6 */7export interface Matcher<T> {8 'pact:matcher:type': string;9 'pact:generator:type'?: string;10 value?: T;11}12export function isMatcher(x: AnyTemplate): x is Matcher<AnyTemplate> {13 return x != null && (x as Matcher<AnyTemplate>).value !== undefined;14}15export type AnyTemplate =16 | AnyJson17 | TemplateMap18 | TemplateArray19 | Matcher<unknown>;20interface TemplateMap {21 [key: string]: AnyJson | AnyTemplate;22}23type TemplateArray = Array<AnyTemplate>;24/**25 * Value must match the given template26 * @param template Template to base the comparison on27 */28export const like = <T extends AnyTemplate>(template: T): Matcher<T> => ({29 'pact:matcher:type': 'type',30 value: template,31});32/**33 * Object where the key itself is ignored, but the value template must match.34 *35 * @param keyTemplate Example key to use36 * @param template Example value template to base the comparison on37 */38export const eachKeyLike = <T extends AnyTemplate>(39 keyTemplate: string,40 template: T41): Matcher<AnyTemplate> => ({42 'pact:matcher:type': 'values',43 value: {44 [keyTemplate]: template,45 },46});47/**48 * Array where each element must match the given template49 * @param template Template to base the comparison on50 */51export const eachLike = <T extends AnyTemplate>(template: T): Matcher<T[]> => ({52 'pact:matcher:type': 'type',53 value: [template],54});55/**56 * Like Matcher with a minimum number of required values57 */58export interface MinLikeMatcher<T> extends Matcher<T> {59 min: number;60}61/**62 * An array that has to have at least one element and each element must match the given template63 * @param template Template to base the comparison on64 * @param count Number of examples to generate, defaults to one65 */66export const atLeastOneLike = <T extends AnyTemplate>(67 template: T,68 count = 169): MinLikeMatcher<T[]> => ({70 min: 1,71 'pact:matcher:type': 'type',72 value: times(() => template, count),73});74/**75 * An array that has to have at least the required number of elements and each element must match the given template76 * @param template Template to base the comparison on77 * @param min Minimum number of elements required in the array78 * @param count Number of examples to generate, defaults to min79 */80export const atLeastLike = <T extends AnyTemplate>(81 template: T,82 min: number,83 count?: number84): MinLikeMatcher<T[]> => {85 const elements = count || min;86 if (count && count < min) {87 throw new Error(88 `atLeastLike has a minimum of ${min} but ${count} elements were requested.` +89 ` Make sure the count is greater than or equal to the min.`90 );91 }92 return {93 min,94 'pact:matcher:type': 'type',95 value: times(() => template, elements),96 };97};98/**99 * Like Matcher with a maximum number of required values100 */101export interface MaxLikeMatcher<T> extends Matcher<T> {102 max: number;103}104/**105 * An array that has to have at most the required number of elements and each element must match the given template106 * @param template Template to base the comparison on107 * @param max Maximum number of elements required in the array108 * @param count Number of examples to generate, defaults to one109 */110export const atMostLike = <T extends AnyTemplate>(111 template: T,112 max: number,113 count?: number114): MaxLikeMatcher<T[]> => {115 const elements = count || 1;116 if (count && count > max) {117 throw new Error(118 `atMostLike has a maximum of ${max} but ${count} elements where requested.` +119 ` Make sure the count is less than or equal to the max.`120 );121 }122 return {123 max,124 'pact:matcher:type': 'type',125 value: times(() => template, elements),126 };127};128/**129 * An array whose size is constrained to the minimum and maximum number of elements and each element must match the given template130 * @param template Template to base the comparison on131 * @param min Minimum number of elements required in the array132 * @param max Maximum number of elements required in the array133 * @param count Number of examples to generate, defaults to one134 */135export const constrainedArrayLike = <T extends AnyTemplate>(136 template: T,137 min: number,138 max: number,139 count?: number140): MinLikeMatcher<T[]> & MaxLikeMatcher<T[]> => {141 const elements = count || min;142 if (count) {143 if (count < min) {144 throw new Error(145 `constrainedArrayLike has a minimum of ${min} but ${count} elements where requested.` +146 ` Make sure the count is greater than or equal to the min.`147 );148 } else if (count > max) {149 throw new Error(150 `constrainedArrayLike has a maximum of ${max} but ${count} elements where requested.` +151 ` Make sure the count is less than or equal to the max.`152 );153 }154 }155 return {156 min,157 max,158 'pact:matcher:type': 'type',159 value: times(() => template, elements),160 };161};162/**163 * Value must be a boolean164 * @param b Boolean example value. Defaults to true if unsupplied165 */166export const boolean = (b = true): Matcher<boolean> => ({167 'pact:matcher:type': 'type',168 value: b,169});170/**171 * Value must be an integer (must be a number and have no decimal places)172 * @param int Example value. If omitted a random value will be generated.173 */174export const integer = (int?: number): Matcher<number> => {175 if (Number.isInteger(int)) {176 return {177 'pact:matcher:type': 'integer',178 value: int,179 };180 }181 if (int) {182 throw new Error(183 `The integer matcher was passed '${int}' which is not an integer.`184 );185 }186 return {187 'pact:generator:type': 'RandomInt',188 'pact:matcher:type': 'integer',189 value: 101,190 };191};192/**193 * Value must be a decimal number (must be a number and have decimal places)194 * @param num Example value. If omitted a random value will be generated.195 */196export const decimal = (num?: number): Matcher<number> => {197 if (Number.isFinite(num)) {198 return {199 'pact:matcher:type': 'decimal',200 value: num,201 };202 }203 if (num) {204 throw new Error(205 `The decimal matcher was passed '${num}' which is not a number.`206 );207 }208 return {209 'pact:generator:type': 'RandomDecimal',210 'pact:matcher:type': 'decimal',211 value: 12.34,212 };213};214/**215 * Value must be a number216 * @param num Example value. If omitted a random integer value will be generated.217 */218export function number(num?: number): Matcher<number> {219 if (num) {220 return {221 'pact:matcher:type': 'number',222 value: num,223 };224 }225 return {226 'pact:generator:type': 'RandomInt',227 'pact:matcher:type': 'number',228 value: 1234,229 };230}231/**232 * Value must be a string233 * @param str Example value234 */235export function string(str = 'some string'): Matcher<string> {236 return {237 'pact:matcher:type': 'type',238 value: str,239 };240}241export interface RegexMatcher extends Matcher<string> {242 regex: string;243 example?: string;244}245/**246 * Value that must match the given regular expression247 * @param pattern Regular Expression to match248 * @param str Example value249 */250export function regex(pattern: RegExp | string, str: string): RegexMatcher {251 if (pattern instanceof RegExp) {252 return {253 'pact:matcher:type': 'regex',254 regex: pattern.source,255 value: str,256 };257 }258 return {259 'pact:matcher:type': 'regex',260 regex: pattern,261 value: str,262 };263}264/**265 * Value that must be equal to the example. This is mainly used to reset the matching rules which cascade.266 * @param value Example value267 */268export const equal = <T extends AnyTemplate>(value: T): Matcher<T> => ({269 'pact:matcher:type': 'equality',270 value,271});272export interface DateTimeMatcher extends Matcher<string> {273 format: string;274}275/**276 * String value that must match the provided datetime format string.277 * @param format Datetime format string. See [Java SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)278 * @param example Example value to use. If omitted a value using the current system date and time will be generated.279 */280export function datetime(format: string, example: string): DateTimeMatcher {281 if (!example) {282 throw new Error(`you must provide an example datetime`);283 }284 return pickBy((v) => !isNil(v), {285 'pact:generator:type': example ? undefined : 'DateTime',286 'pact:matcher:type': 'timestamp',287 format,288 value: example,289 });290}291/**292 * String value that must match the provided datetime format string.293 * @param format Datetime format string. See [Java SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)294 * @param example Example value to use. If omitted a value using the current system date and time will be generated.295 */296export function timestamp(format: string, example: string): DateTimeMatcher {297 if (!example) {298 throw new Error(`you must provide an example timestamp`);299 }300 return datetime(format, example);301}302/**303 * String value that must match the provided time format string.304 * @param format Time format string. See [Java SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)305 * @param example Example value to use. If omitted a value using the current system time will be generated.306 */307export function time(format: string, example: string): DateTimeMatcher {308 if (!example) {309 throw new Error(`you must provide an example time`);310 }311 return {312 'pact:generator:type': 'Time',313 'pact:matcher:type': 'time',314 format,315 value: example,316 };317}318/**319 * String value that must match the provided date format string.320 * @param format Date format string. See [Java SimpleDateFormat](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html)321 * @param example Example value to use. If omitted a value using the current system date will be generated.322 */323export function date(format: string, example: string): DateTimeMatcher {324 if (!example) {325 throw new Error(`you must provide an example date`);326 }327 return {328 format,329 'pact:generator:type': 'Date',330 'pact:matcher:type': 'date',331 value: example,332 };333}334/**335 * Value that must include the example value as a substring.336 * @param value String value to include337 */338export function includes(value: string): Matcher<string> {339 return {340 'pact:matcher:type': 'include',341 value,342 };343}344/**345 * Value that must be null. This will only match the JSON Null value. For other content types, it will346 * match if the attribute is missing.347 */348export function nullValue(): Matcher<null> {349 return {350 'pact:matcher:type': 'null',351 };352}353function stringFromRegex(r: RegExp): string {354 return new RandExp(r).gen();355}356/**357 * Matches a URL composed of a base path and a list of path fragments358 * @param basePath Base path of the URL. If null, will use the base URL from the mock server.359 * @param pathFragments list of path fragments, can be regular expressions360 */361export function url2(362 basePath: string | null,363 pathFragments: Array<string | RegexMatcher | RegExp>364): RegexMatcher {365 const regexpr = [366 '.*(',367 ...pathFragments.map((p) => {368 if (p instanceof RegExp) {369 return `\\/${p.source}`;370 }371 if (p instanceof Object && p['pact:matcher:type'] === 'regex') {372 return `\\/${p.regex}`;373 }374 return `\\/${p.toString()}`;375 }),376 ].join('');377 const example = [378 basePath || 'http://localhost:8080',379 ...pathFragments.map((p) => {380 if (p instanceof RegExp) {381 return `/${stringFromRegex(p)}`;382 }383 if (p instanceof Object && p['pact:matcher:type'] === 'regex') {384 return `/${p.value}`;385 }386 return `/${p.toString()}`;387 }),388 ].join('');389 // Temporary fix for inconsistancies between matchers and generators. Matchers use "value" attribute for390 // example values, while generators use "example"391 if (basePath == null) {392 return {393 'pact:matcher:type': 'regex',394 'pact:generator:type': 'MockServerURL',395 regex: `${regexpr})$`,396 value: example,397 example,398 };399 }400 return {401 'pact:matcher:type': 'regex',402 regex: `${regexpr})$`,403 value: example,404 };405}406/**407 * Matches a URL composed of a list of path fragments. The base URL from the mock server will be used.408 * @param pathFragments list of path fragments, can be regular expressions409 */410export function url(411 pathFragments: Array<string | RegexMatcher | RegExp>412): RegexMatcher {413 return url2(null, pathFragments);414}415export interface ArrayContainsMatcher extends Matcher<AnyTemplate[]> {416 variants: Array<AnyTemplate>;417}418/**419 * Matches the items in an array against a number of variants. Matching is successful if each variant420 * occurs once in the array. Variants may be objects containing matching rules.421 */422export function arrayContaining(423 ...variants: AnyTemplate[]424): ArrayContainsMatcher {425 return {426 'pact:matcher:type': 'arrayContains',427 variants,428 };429}430export interface ProviderStateInjectedValue<T> extends Matcher<T> {431 expression: string;432}433/**434 * Marks an item to be injected from the provider state435 * @param expression Expression to lookup in the provider state context436 * @param exampleValue Example value to use in the consumer test437 */438export function fromProviderState<V extends AnyJson>(439 expression: string,440 exampleValue: V441): ProviderStateInjectedValue<V> {442 return {443 'pact:matcher:type': 'type',444 'pact:generator:type': 'ProviderState',445 expression,446 value: exampleValue,447 };448}449/**450 * Match a universally unique identifier (UUID). Random values will be used for examples if no example is given.451 */452export function uuid(example?: string): RegexMatcher {453 const regexStr =454 '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';455 if (example) {456 const regexpr = new RegExp(`^${regexStr}$`);457 if (!example.match(regexpr)) {458 throw new Error(459 `regex: Example value '${example}' does not match the UUID regular expression '${regexStr}'`460 );461 }462 return {463 'pact:matcher:type': 'regex',464 regex: regexStr,465 value: example,466 };467 }468 return {469 'pact:matcher:type': 'regex',470 regex: regexStr,471 'pact:generator:type': 'Uuid',472 value: 'e2490de5-5bd3-43d5-b7c4-526e33f71304',473 };474}475export const matcherValueOrString = (obj: unknown): string => {476 if (typeof obj === 'string') return obj;477 return JSON.stringify(obj);478};479/**480 * Recurse the object removing any underlying matching guff, returning the raw481 * example content.482 */483export function reify(input: AnyTemplate): AnyJson {484 if (isMatcher(input)) {485 return reify(input.value as AnyTemplate);486 }487 if (Object.prototype.toString.call(input) === '[object Array]') {488 return (input as Array<AnyTemplate>).map(reify);489 }490 if (input !== null && typeof input === 'object') {491 return Object.keys(input).reduce(492 (acc: JsonMap, propName: string) => ({493 ...acc,494 [propName]: reify((input as Record<string, AnyTemplate>)[propName]),495 }),496 {}497 );498 }499 return input;500}...
Using AI Code Generation
1const { Matchers } = require('@pact-foundation/pact');2const body = {3 name: Matchers.somethingLike('John'),4 age: Matchers.somethingLike(20),5 address: Matchers.somethingLike('123, ABC Street'),6 phone: Matchers.somethingLike('1234567890'),7 email: Matchers.somethingLike('
Using AI Code Generation
1const path = require('path');2const { Matchers, Verifier } = require('@pact-foundation/pact');3const opts = {4 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')],5};6const verifier = new Verifier(opts);7verifier.verifyProvider().then(output => {8 console.log('Pact Verification Complete!');9 console.log(output);10});11 at output (/Users/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/pact-js/node_modules/@pact-foundation/pact-node/src/verifier.js:46:15)12 at processTicksAndRejections (internal/process/task_queues.js:97:5)13 at async run (/Users/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/pact-js/node_modules/@pact-foundation/pact-node/src/verifier.js:25:3)14 at async Object.exports.verifyProvider (/Users/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/pact-js/node_modules/@pact-foundation/pact-node/src/verifier.js:18:3)15 at async Object.<anonymous> (/Users/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/xxxxxx/pact-js/test2.js:17:5)16 at async Module._compile (internal/modules/cjs/loader.js:1137:30)17 at async Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)18 at async Module.load (internal/modules/cjs/loader.js:985:32)19 at async Function.Module._load (internal/modules/cjs
Using AI Code Generation
1const { Matchers } = require('@pact-foundation/pact');2const like = Matchers.like;3const eachLike = Matchers.eachLike;4const atMostLike = Matchers.atMostLike;5const expected = {6 friends: eachLike({7 friends: atMostLike(2, {8 friends: eachLike({9 friends: eachLike({10 friends: eachLike({11 friends: atMostLike(2, {12 friends: eachLike({13 friends: eachLike({14 friends: eachLike({15 friends: atMostLike(2, {16 friends: eachLike({17 friends: eachLike({18 friends: eachLike({19 friends: eachLike({20 friends: atMostLike(2, {21 friends: eachLike({22 friends: eachLike({
Using AI Code Generation
1var pact = require('pact-foundation/pact-node');2var path = require('path');3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6var expect = chai.expect;7var axios = require('axios');8describe('Pact', function () {9 var provider = pact({10 log: path.resolve(process.cwd(), 'logs', 'pact.log'),11 dir: path.resolve(process.cwd(), 'pacts'),12 });13 before(function () {14 return provider.setup();15 });16 after(function () {17 return provider.finalize();18 });19 afterEach(function () {20 return provider.verify();21 });22 describe('Pact with a NodeJS consumer', function () {23 describe('when a request to get all users is made', function () {24 before(function (done) {25 var expectedResponse = {26 {
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!!