Best JavaScript code snippet using fast-check-monorepo
uniqueArray.spec.ts
Source:uniqueArray.spec.ts
...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 }378 switch (comparator) {379 case 'IsStrictlyEqual':380 return (a, b) => a === b;381 case 'SameValue':382 return (a, b) => Object.is(a, b);383 case 'SameValueZero':384 return (a, b) => (a === 0 && b === 0) || Object.is(a, b);385 }386}387type SelectorType<T = unknown, U = unknown> = UniqueArrayConstraints<T, U>['selector'];388function selectorArbitrary(): fc.Arbitrary<SelectorType> {389 return fc.func(fc.anything());390}391function resolveSelectorFunction<T, U>(selector: SelectorType<T, U> | undefined): (a: unknown) => unknown {392 if (selector === undefined) {393 return (a) => a;394 }395 return selector as (a: unknown) => unknown;...
Using AI Code Generation
1const fc = require('fast-check');2const { selectorArbitrary } = require('fast-check/lib/arbitrary/selectorArbitrary');3const { integer } = require('fast-check/lib/arbitrary/integer');4const { array } = require('fast-check/lib/arbitrary/array');5const { record } = require('fast-check/lib/arbitrary/record');6const { tuple } = require('fast-check/lib/arbitrary/tuple');7const { set } = require('fast-check/lib/arbitrary/set');8const { string } = require('fast-check/lib/arbitrary/string');9const { oneof } = require('fast-check/lib/arbitrary/oneof');10const { constantFrom } = require('fast-check/lib/arbitrary/constantFrom');11const { option } = require('fast-check/lib/arbitrary/option');12const { json } = require('fast-check/lib/arbitrary/json');13const { boolean } = require('fast-check/lib/arbitrary/boolean');14const { map } = require('fast-check/lib/arbitrary/_internals/mappers/Map');15const { set } = require('fast-check/lib/arbitrary/_internals/mappers/Set');16const { array } = require('fast-check/lib/arbitrary/_internals/mappers/Array');17const { object } = require('fast-check/lib/arbitrary/_internals/mappers/Object');18const { date } = require('fast-check/lib/arbitrary/date');19const { bigInt } = require('fast-check/lib/arbitrary/bigInt');20const { merge } = require('fast-check/lib/arbitrary/_internals/mappers/Merge');21const { cloneMethod } = require('fast-check/lib/arbitrary/_internals/mappers/CloneMethod');22const { cloneFunction } = require('fast-check/lib/arbitrary/_internals/mappers/CloneFunction');23const { removeKeys } = require('fast-check/lib/arbitrary/_internals/mappers/RemoveKeys');24const { mapToConstant } = require('fast-check/lib/arbitrary/_internals/mappers/MapToConstant');25const { mapToConstantFrom } = require('fast-check/lib/arbitrary/_internals/mappers/MapToConstantFrom');26const { mapToUndefined } = require('fast-check/lib/arbitrary/_internals/mappers/MapToUndefined');27const { mapToNull } = require('fast-check/lib/arbitrary/_internals/mappers/MapToNull');28const { mapToNext } = require('fast-check/lib/arbitrary
Using AI Code Generation
1const fc = require("fast-check");2const { selectorArbitrary } = require("fast-check-monorepo");3const arb = selectorArbitrary(fc.nat(), fc.nat());4fc.assert(5 fc.property(arb, (selector) => {6 return selector.length === 2;7 })8);9 triggerUncaughtException(err, true /* fromPromise */);10Error: Property failed after 1 tests, shrunk 0 time(s)11 at Object.<anonymous> (/home/.../test.js:8:11)12 at Module._compile (node:internal/modules/cjs/loader:1108:14)13 at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)14 at Module.load (node:internal/modules/cjs/loader:988:32)15 at Function.Module._load (node:internal/modules/cjs/loader:828:14)16 at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)17 at node:internal/main/run_main_module:17:47 {18}
Using AI Code Generation
1const fc = require('fast-check');2const {selectorArbitrary} = require('fast-check-monorepo');3fc.assert(4 fc.property(selectorArbitrary(), (selector) => {5 })6);7const fc = require('fast-check');8const {selectorArbitrary} = require('fast-check-monorepo');9fc.assert(10 fc.property(selectorArbitrary(), (selector) => {11 })12);13npm ERR! 404 You should bug the author to publish it (or use the name yourself!)14npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
Using AI Code Generation
1const { selectorArbitrary } = require('../lib/index.js');2const fc = require('fast-check');3const arb = selectorArbitrary(fc.string(), fc.string());4fc.assert(5 fc.property(arb, (s) => {6 console.log(s);7 return true;8 })9);10const { selectorArbitrary } = require('../lib/index.js');11const fc = require('fast-check');12const arb = selectorArbitrary(fc.string(), fc.string(), fc.object());13fc.assert(14 fc.property(arb, (s) => {15 console.log(s);16 return true;17 })18);19In the above code, selectorArbitrary() is used to generate arbitrary selector strings. The first argument of selectorArbitrary() is a function that returns a fast-check arbitrary for the selector. The second argument is a function that returns a fast-check arbitrary for the value. The third argument is a function that returns
Using AI Code Generation
1const fc = require('fast-check');2const { selectorArbitrary } = require('fast-check-monorepo');3const arb = selectorArbitrary(4);5const array = arb.generate(fc.random());6console.log(array);7const selector = arb.generateSelector(fc.random());8console.log(selector);9const selected = arb.applySelector(array, selector);10console.log(selected);11const selected2 = arb.generateAndApply(fc.random());12console.log(selected2);13const selected3 = arb.generateAndApplyAndCheck(fc.random());14console.log(selected3);15const selected4 = arb.generateAndApplyAndCheckAndPrint(fc.random());16console.log(selected4);17const selected5 = arb.generateAndApplyAndCheckAndPrintArray(fc.random());18console.log(selected5);19const selected6 = arb.generateAndApplyAndCheckAndPrintSelector(fc.random());20console.log(selected6);
Using AI Code Generation
1const fc = require('fast-check');2const { selectorArbitrary } = require('fast-check-monorepo');3const makeObject = (keys, values) => {4 let result = {};5 for (let i = 0; i < keys.length; i++) {6 result[keys[i]] = values[i];7 }8 return result;9};10 .tuple(fc.array(fc.string()), fc.array(fc.integer()))11 .map(([keys, values]) => makeObject(keys, values));12const selector = selectorArbitrary(objectArbitrary);13fc.assert(14 fc.property(selector, selector, (s1, s2) => {15 const o = makeObject(['a', 'b', 'c'], [1, 2, 3]);16 return s1(o) === s2(o);17 })18);
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!!