How to use comparatorArbitrary method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

uniqueArray.spec.ts

Source:uniqueArray.spec.ts Github

copy

Full Screen

...173 .record(174 {175 minLength: fc.nat({ max: 2 ** 31 - 1 }),176 maxLength: fc.nat({ max: 2 ** 31 - 1 }),177 comparator: comparatorArbitrary(),178 selector: selectorArbitrary(),179 depthIdentifier: fc.string(),180 },181 { requiredKeys: [] }182 )183 .map((constraints) =>184 constraints.minLength !== undefined &&185 constraints.maxLength !== undefined &&186 constraints.minLength > constraints.maxLength187 ? ({188 ...constraints,189 minLength: constraints.maxLength,190 maxLength: constraints.minLength,191 } as UniqueArrayConstraints<unknown, unknown>)192 : ({ ...constraints } as UniqueArrayConstraints<unknown, unknown>)193 ),194 (config, constraints) => {195 // Arrange196 const { instance: childInstance } = fakeArbitrary<unknown>();197 const { instance, filter } = fakeArbitrary<unknown[]>();198 const ArrayArbitrary = jest.spyOn(ArrayArbitraryMock, 'ArrayArbitrary');199 ArrayArbitrary.mockImplementation(() => instance as ArrayArbitraryMock.ArrayArbitrary<unknown>);200 filter.mockReturnValue(instance);201 // Act202 const arb = withConfiguredGlobal(config, () => uniqueArray(childInstance, constraints));203 // Assert204 expect(ArrayArbitrary).toHaveBeenCalledWith(205 childInstance,206 constraints.minLength !== undefined ? constraints.minLength : expect.any(Number),207 expect.any(Number),208 constraints.maxLength !== undefined ? constraints.maxLength : expect.any(Number),209 constraints.depthIdentifier,210 expect.any(Function),211 []212 );213 expect(arb).toBe(instance);214 }215 )216 );217 });218 it('should throw when minimum length is greater than maximum one', () => {219 fc.assert(220 fc.property(221 sizeRelatedGlobalConfigArb,222 fc.nat({ max: 2 ** 31 - 1 }),223 fc.nat({ max: 2 ** 31 - 1 }),224 fc.option(comparatorArbitrary(), { nil: undefined }),225 fc.option(selectorArbitrary(), { nil: undefined }),226 (config, aLength, bLength, comparator, selector) => {227 // Arrange228 fc.pre(aLength !== bLength);229 const [minLength, maxLength] = aLength < bLength ? [bLength, aLength] : [aLength, bLength];230 const { instance: childInstance } = fakeArbitrary<unknown>();231 // Act / Assert232 expect(() =>233 withConfiguredGlobal(config, () =>234 uniqueArray(childInstance, { minLength, maxLength, comparator, selector })235 )236 ).toThrowError();237 }238 )239 );240 });241});242describe('uniqueArray (integration)', () => {243 type Extra = UniqueArrayConstraints<unknown, unknown>;244 const extraParameters: fc.Arbitrary<Extra> = fc245 .tuple(246 fc.nat({ max: 5 }),247 fc.nat({ max: 30 }),248 fc.boolean(),249 fc.boolean(),250 fc.option(fc.func(fc.integer()), { nil: undefined }),251 fc.option(comparatorArbitrary(), { nil: undefined })252 )253 .map(([min, gap, withMin, withMax, selector, comparator]) => {254 // We only apply selector/comparator in case the minimal number of items requested can be reached with the selector/comparator.255 // eg.: selector = v => 0, means that we will have at most 1 value in the array, never more, so it cannot be used with min > 1256 const requestedMin = withMin ? min : 0;257 let selectorEnabled = requestedMin === 0 || selector === undefined;258 let comparatorEnabled = requestedMin === 0 || comparator === undefined;259 const sampleSize = 50;260 const sampledSelectedValues = new Set<unknown>();261 const sampledSelectedAndComparedValues: unknown[] = [];262 const resolvedSelector = resolveSelectorFunction(selector);263 const resolvedComparator = resolveComparatorFunction(comparator);264 for (let v = 0; v !== sampleSize && (!selectorEnabled || !comparatorEnabled); ++v) {265 const selected = resolvedSelector(v); // either v (integer in 0..sampleSize) or an integer (by construct of selector)266 sampledSelectedValues.add(selected);267 selectorEnabled = selectorEnabled || sampledSelectedValues.size >= requestedMin;268 if (!comparatorEnabled && comparator !== undefined) {269 if (sampledSelectedAndComparedValues.every((p) => !resolvedComparator(p, selected))) {270 // Selected is "different" from all the other known values271 sampledSelectedAndComparedValues.push(selected);272 comparatorEnabled = comparatorEnabled || sampledSelectedAndComparedValues.length >= requestedMin;273 selectorEnabled = selectorEnabled || comparatorEnabled; // comparator enabled unlocks selector too274 }275 }276 }277 return {278 minLength: withMin ? min : undefined,279 maxLength: withMax ? min + gap : undefined,280 selector: selectorEnabled ? selector : undefined,281 comparator: comparatorEnabled ? comparator : undefined,282 };283 });284 const isCorrect = (value: number[], extra: Extra) => {285 if (extra.minLength !== undefined) {286 expect(value.length).toBeGreaterThanOrEqual(extra.minLength);287 }288 if (extra.maxLength !== undefined) {289 expect(value.length).toBeLessThanOrEqual(extra.maxLength);290 }291 for (const v of value) {292 expect(typeof v).toBe('number');293 }294 const resolvedSelector = resolveSelectorFunction(extra.selector);295 const resolvedComparator = resolveComparatorFunction(extra.comparator);296 const alreadySeen: unknown[] = [];297 for (const v of value) {298 const selected = resolvedSelector(v);299 const matchingEntry = alreadySeen.some((e) => resolvedComparator(e, selected));300 expect(matchingEntry).toBe(false);301 alreadySeen.push(selected);302 }303 };304 const integerUpTo10000AndNaNOrMinusZero = new FakeIntegerArbitrary(-2, 10000).map(305 (v) => (v === -2 ? Number.NaN : v === -1 ? -0 : v),306 (v) => {307 if (typeof v !== 'number' || v === -1 || v === -2) throw new Error('');308 return Object.is(v, Number.NaN) ? -2 : Object.is(v, -0) ? -1 : v;309 }310 );311 const uniqueArrayBuilder = (extra: Extra) => uniqueArray(integerUpTo10000AndNaNOrMinusZero, extra);312 it('should produce the same values given the same seed', () => {313 assertProduceSameValueGivenSameSeed(uniqueArrayBuilder, { extraParameters });314 });315 it('should only produce correct values', () => {316 assertProduceCorrectValues(uniqueArrayBuilder, isCorrect, { extraParameters });317 });318 it('should produce values seen as shrinkable without any context', () => {319 assertProduceValuesShrinkableWithoutContext(uniqueArrayBuilder, { extraParameters });320 });321 it('should be able to shrink to the same values without initial context', () => {322 assertShrinkProducesSameValueWithoutInitialContext(uniqueArrayBuilder, { extraParameters });323 });324 // Property: should preserve strictly smaller ordering in shrink325 // Is not applicable in the case of `set` as some values may not be in the "before" version326 // of the array while they can suddenly appear on shrink. They might have been hidden because327 // another value inside the array shadowed them. While on shrink those entries shadowing others328 // may have disappear.329 it.each`330 source | constraints331 ${[2, 4, 8] /* not large enough */} | ${{ minLength: 4 }}332 ${[2, 4, 8] /* too large */} | ${{ maxLength: 2 }}333 ${[2, 4, 8] /* not unique for selector */} | ${{ selector: (item: number) => Math.floor(item / 5) }}334 ${[2, 4, 8] /* not unique for comparator */} | ${{ comparator: (a: number, b: number) => Math.abs(a - b) <= 2 }}335 `('should not be able to generate $source with fc.uniqueArray(arb, $constraints)', ({ source, constraints }) => {336 // Arrange / Act337 const arb = uniqueArray(new FakeIntegerArbitrary(0, 1000), constraints);338 const out = arb.canShrinkWithoutContext(source);339 // Assert340 expect(out).toBe(false);341 });342 it.each`343 rawValue | constraints344 ${[2, 4, 8, 16, 32, 64]} | ${{}}345 ${[2, 4, 8]} | ${{}}346 ${[2, 4, 8]} | ${{ minLength: 2 }}347 ${[2, 4, 8]} | ${{ minLength: 3 }}348 ${[2, 8]} | ${{ selector: (item: number) => Math.floor(item / 5) }}349 ${[2, 8]} | ${{ comparator: (a: number, b: number) => Math.abs(a - b) <= 2 }}350 `('should be able to shrink $rawValue with fc.uniqueArray(arb, $constraints)', ({ rawValue, constraints }) => {351 // Arrange352 const arb = uniqueArray(new FakeIntegerArbitrary(0, 1000), constraints);353 const value = new Value(rawValue, undefined);354 // Act355 const renderedTree = renderTree(buildShrinkTree(arb, value, { numItems: 100 })).join('\n');356 // Assert357 expect(arb.canShrinkWithoutContext(rawValue)).toBe(true);358 expect(renderedTree).toMatchSnapshot();359 });360});361// Helpers362type ComparatorType<T = unknown, U = unknown> = UniqueArrayConstraints<T, U>['comparator'];363function comparatorArbitrary(): fc.Arbitrary<ComparatorType> {364 return fc.oneof(365 fc.constantFrom<ComparatorType>('IsStrictlyEqual', 'SameValue', 'SameValueZero'),366 fc.compareFunc().map((f) => (a: unknown, b: unknown) => f(a, b) === 0)367 );368}369function resolveComparatorFunction<T, U>(370 comparator: ComparatorType<T, U> | undefined371): (a: unknown, b: unknown) => boolean {372 if (comparator === undefined) {373 return (a, b) => Object.is(a, b);374 }375 if (typeof comparator === 'function') {376 return comparator as (a: unknown, b: unknown) => boolean;377 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const {comparatorArbitrary} = require('fast-check-monorepo');3const arb = comparatorArbitrary(fc.integer(), (a, b) => a - b);4fc.assert(fc.property(arb, (a) => a === 0));5const fc = require('fast-check');6const {comparatorArbitrary} = require('fast-check');7const arb = comparatorArbitrary(fc.integer(), (a, b) => a - b);8fc.assert(fc.property(arb, (a) => a === 0));9const fc = require('fast-check-monorepo');10const {comparatorArbitrary} = require('fast-check-monorepo');11const arb = comparatorArbitrary(fc.integer(), (a, b) => a - b);12fc.assert(fc.property(arb, (a) => a === 0));13const fc = require('fast-check');14const {comparatorArbitrary} = require('fast-check');

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { comparatorArbitrary } = require('fast-check/lib/arbitrary/comparatorArbitrary');3const { array } = require('fast-check/lib/arbitrary/array');4const { frequency } = require('fast-check/lib/arbitrary/frequency');5const { constantFrom } = require('fast-check/lib/arbitrary/constantFrom');6const { tuple } = require('fast-check/lib/arbitrary/tuple');7const customComparator = comparatorArbitrary(8 frequency(9 { weight: 1, arbitrary: constantFrom(-1, 0, 1) },10 { weight: 4, arbitrary: tuple(array(fc.integer()), array(fc.integer())).map(([a, b]) => a.length - b.length) }11);12fc.assert(13 fc.property(array(fc.integer()), array(fc.integer()), (a, b) => {14 const aIsGreater = customComparator.compare(a, b) > 0;15 const bIsGreater = customComparator.compare(b, a) > 0;16 })17);18const fc = require('fast-check');19const { tuple } = require('fast-check/lib/arbitrary/tuple');20const { array } = require('fast-check/lib/arbitrary/array');21const { integer } = require('fast-check/lib/arbitrary/integer');22const arrayArb = array(integer(0, 10));23const tupleArb = tuple(arrayArb, arrayArb);24fc.assert(25 fc.property(tupleArb, ([a, b]) => {26 const aIsGreater = a.length > b.length;27 const bIsGreater = b.length > a.length;28 })29);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { comparatorArbitrary } = require('fast-check-monorepo');3const myComparator = (a, b) => a - b;4const myArbitrary = fc.integer(0, 100);5const myComparedArbitrary = comparatorArbitrary(myComparator, myArbitrary);6fc.assert(fc.property(myComparedArbitrary, (arr) => {7 return arr.slice(1).every((e, i) => myComparator(arr[i], e) <= 0);8}));9const fc = require('fast-check');10const { comparatorArbitrary } = require('fast-check-monorepo');11const myComparator = (a, b) => a.age - b.age;12const myArbitrary = fc.record({13 name: fc.string(),14 age: fc.integer(0, 100)15});16const myComparedArbitrary = comparatorArbitrary(myComparator, myArbitrary);17fc.assert(fc.property(myComparedArbitrary, (arr) => {18 return arr.slice(1).every((e, i) => myComparator(arr[i], e) <= 0);19}));

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { comparatorArbitrary } = require("fast-check-monorepo");3const arb = comparatorArbitrary(fc.integer());4fc.assert(fc.property(arb, (cmp) => {5 expect(cmp(1, 2)).toBeLessThan(0);6 expect(cmp(2, 1)).toBeGreaterThan(0);7 expect(cmp(1, 1)).toBe(0);8}));9const fc = require("fast-check");10const { comparatorArbitrary } = require("fast-check");11const arb = comparatorArbitrary(fc.integer());12fc.assert(fc.property(arb, (cmp) => {13 expect(cmp(1, 2)).toBeLessThan(0);14 expect(cmp(2, 1)).toBeGreaterThan(0);15 expect(cmp(1, 1)).toBe(0);16}));17const fc = require("fast-check");18const { comparatorArbitrary } = require("fast-check");19const arb = comparatorArbitrary(fc.integer());20fc.assert(fc.property(arb, (cmp) => {21 expect(cmp(1, 2)).toBeLessThan(0);22 expect(cmp(2, 1)).toBeGreaterThan(0);23 expect(cmp(1, 1)).toBe(0);24}));25const fc = require("fast-check");26const { comparatorArbitrary } = require("fast-check");27const arb = comparatorArbitrary(fc.integer());28fc.assert(fc.property(arb, (cmp) => {29 expect(cmp(1, 2)).toBeLessThan(0);30 expect(cmp(2, 1)).toBeGreaterThan(0);31 expect(cmp(1, 1)).toBe(0);32}));33const fc = require("fast-check");34const { comparatorArbitrary } = require("fast-check");35const arb = comparatorArbitrary(fc.integer());36fc.assert(fc.property(arb, (cmp) => {37 expect(cmp(1, 2)).toBeLessThan(0);38 expect(cmp(2, 1)).toBeGreaterThan(0);39 expect(cmp(1, 1)).toBe(0);40}));41const fc = require("fast-check");42const { comparatorArbitrary } =

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { comparatorArbitrary } = require("fast-check-monorepo");3const naturalComparator = (a, b) => a - b;4const arb = comparatorArbitrary(naturalComparator, fc.integer(), fc.integer());5fc.assert(6 fc.property(fc.array(arb), (array) => {7 const sortedArray = array.sort(naturalComparator);8 for (let i = 0; i < sortedArray.length - 1; ++i) {9 if (sortedArray[i] > sortedArray[i + 1]) {10 return false;11 }12 }13 return true;14 })15);16const fc = require("fast-check");17const { comparatorArbitrary } = require("fast-check-monorepo");18const naturalComparator = (a, b) => a - b;19const arb = comparatorArbitrary(naturalComparator, fc.integer(), fc.integer());20fc.assert(21 fc.property(fc.array(arb), (array) => {22 const sortedArray = array.sort(naturalComparator);23 for (let i = 0; i < sortedArray.length - 1; ++i) {24 if (sortedArray[i] > sortedArray[i + 1]) {25 return false;26 }27 }28 return true;29 })30);31const fc = require("fast-check");32const { comparatorArbitrary } = require("fast-check-monorepo");33const naturalComparator = (a, b) => a - b;34const arb = comparatorArbitrary(naturalComparator, fc.integer(), fc.integer());35fc.assert(36 fc.property(fc.array(arb), (array) => {37 const sortedArray = array.sort(naturalComparator);38 for (let i = 0; i < sortedArray.length - 1; ++i) {39 if (sortedArray[i

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { comparatorArbitrary } = require("fast-check-monorepo");3const { isSorted } = require("is-sorted");4const arrayArbitrary = fc.array(fc.integer());5const comparatorArbitrary = comparatorArbitrary(arrayArbitrary);6fc.assert(7 fc.property(arrayArbitrary, comparatorArbitrary, (array, comparator) => {8 const sortedArray = array.sort(comparator);9 return isSorted(sortedArray, comparator);10 })11);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const comparatorArbitrary = require("fast-check/lib/combinators/comparatorArbitrary.js");3const {ComparableValue} = require("fast-check/lib/combinators/ComparableValue.js");4const {ComparableValueObject} = require("fast-check/lib/combinators/ComparableValueObject.js");5const arbitrary = comparatorArbitrary(6 fc.nat(),7 (a, b) => a - b8);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require("fast-check");2const { comparatorArbitrary } = require("fast-check-monorepo");3const { compare } = require("fast-check-monorepo/src/comparator/Comparator");4const { compareNumbers } = require("fast-check-monorepo/src/comparator/NumberComparator");5const { compareStrings } = require("fast-check-monorepo/src/comparator/StringComparator");6const comparator = comparatorArbitrary(compareNumbers, compareStrings);7fc.assert(8 fc.property(fc.array(fc.integer()), fc.array(fc.string()), (a, b) => {9 const result = compare(a, b);10 const result2 = comparator.compare(a, b);11 return result === result2;12 })13);

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2const { comparatorArbitrary } = require('fast-check/lib/comparator/ComparatorArbitrary');3const obj1 = {4};5const obj2 = {6};7const objArbitrary = comparatorArbitrary(fc.object(), fc.object());8fc.assert(9 fc.property(objArbitrary, ([obj1, obj2]) => {10 return obj1.a === obj2.a && obj1.b === obj2.b && obj1.c === obj2.c;11 })12);13const fc = require('fast-check');14const { comparatorArbitrary } = require('fast-check/lib/comparator/ComparatorArbitrary');15const obj1 = {16};17const obj2 = {18};19const objArbitrary = comparatorArbitrary(fc.object(), fc.object());20fc.assert(21 fc.property(objArbitrary, ([obj1, obj2]) => {22 return obj1.a === obj2.a && obj1.b === obj2.b && obj1.c === obj2.c;23 })24);25const fc = require('fast-check');26const { comparatorArbitrary } = require('fast-check/lib/comparator/ComparatorArbitrary');27const obj1 = {28};29const obj2 = {30};31const objArbitrary = comparatorArbitrary(fc.object(), fc.object());32fc.assert(33 fc.property(objArbitrary, ([obj1, obj2]) => {34 return obj1.a === obj2.a && obj1.b === obj2.b && obj1.c === obj2.c;35 })36);

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 fast-check-monorepo 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