### Setup Project with Bun Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Use Bun to download the project template and install dependencies. ```bash bun x degit dubzzz/fast-check/website/templates/fast-check-tutorial fast-check-tutorial cd fast-check-tutorial npm i ``` -------------------------------- ### Setup Project with pnpm Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Use pnpm to download the project template and install dependencies. ```bash pnpm dlx degit dubzzz/fast-check/website/templates/fast-check-tutorial fast-check-tutorial cd fast-check-tutorial npm i ``` -------------------------------- ### Setup Project with npm Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Use npm to download the project template and install dependencies. ```bash npx degit dubzzz/fast-check/website/templates/fast-check-tutorial fast-check-tutorial cd fast-check-tutorial npm i ``` -------------------------------- ### Setup Project with Yarn Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Use Yarn to download the project template and install dependencies. ```bash yarn dlx degit dubzzz/fast-check/website/templates/fast-check-tutorial fast-check-tutorial cd fast-check-tutorial npm i ``` -------------------------------- ### Install fast-check and @fast-check/jest with Bun Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-jest Install the necessary libraries for your project using Bun. ```bash bun add --dev fast-check @fast-check/jest ``` -------------------------------- ### Install @fast-check/vitest with Bun Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-vitest Install the necessary libraries for property-based testing with Vitest using Bun. ```bash bun add --dev fast-check @fast-check/vitest ``` -------------------------------- ### Install fast-check with Bun Source: https://fast-check.dev/docs/introduction/getting-started Install fast-check as a development dependency using Bun. ```bash bun add --dev fast-check ``` -------------------------------- ### Install fast-check and @fast-check/jest with npm Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-jest Install the necessary libraries for your project using npm. ```bash npm install --save-dev fast-check @fast-check/jest ``` -------------------------------- ### Install @fast-check/vitest with npm Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-vitest Install the necessary libraries for property-based testing with Vitest using npm. ```bash npm install --save-dev fast-check @fast-check/vitest ``` -------------------------------- ### Install experimental fast-check with Bun Source: https://fast-check.dev/docs/introduction/getting-started Install the latest experimental version of fast-check from pkg.pr.new using Bun. Use with caution as APIs may be unstable. ```bash bun add --dev https://pkg.pr.new/fast-check@main ``` -------------------------------- ### Install fast-check with pnpm Source: https://fast-check.dev/docs/introduction/getting-started Install fast-check as a development dependency using pnpm. ```bash pnpm add --save-dev fast-check ``` -------------------------------- ### Vitest Setup File for Global Settings Source: https://fast-check.dev/docs/configuration/global-settings Import `fast-check` and call `configureGlobal` within the Vitest setup file. ```javascript import fc from 'fast-check'; fc.configureGlobal({ numRuns: 10 }); ``` -------------------------------- ### Install fast-check and @fast-check/jest with pnpm Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-jest Install the necessary libraries for your project using pnpm. ```bash pnpm add --save-dev fast-check @fast-check/jest ``` -------------------------------- ### Install @fast-check/vitest with pnpm Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-vitest Install the necessary libraries for property-based testing with Vitest using pnpm. ```bash pnpm add --save-dev fast-check @fast-check/vitest ``` -------------------------------- ### Install fast-check with Yarn Source: https://fast-check.dev/docs/introduction/getting-started Install fast-check as a development dependency using Yarn. ```bash yarn add --dev fast-check ``` -------------------------------- ### Install fast-check and @fast-check/jest with Yarn Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-jest Install the necessary libraries for your project using Yarn. ```bash yarn add --dev fast-check @fast-check/jest ``` -------------------------------- ### Install @fast-check/vitest with Yarn Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-vitest Install the necessary libraries for property-based testing with Vitest using Yarn. ```bash yarn add --dev fast-check @fast-check/vitest ``` -------------------------------- ### Install experimental fast-check with Yarn Source: https://fast-check.dev/docs/introduction/getting-started Install the latest experimental version of fast-check from pkg.pr.new using Yarn. Use with caution as APIs may be unstable. ```bash yarn add --dev https://pkg.pr.new/fast-check@main ``` -------------------------------- ### Install fast-check with npm Source: https://fast-check.dev/docs/introduction/getting-started Install fast-check as a development dependency using npm. ```bash npm install --save-dev fast-check ``` -------------------------------- ### Per-Test Settings Example Source: https://fast-check.dev/docs/configuration/global-settings Demonstrates how to specify settings like `numRuns` for individual tests. ```javascript test('test #1', () => { fc.assert(myProp1, { numRuns: 10 }); }); test('test #2', () => { fc.assert(myProp2, { numRuns: 10 }); }); test('test #3', () => { fc.assert(myProp3, { numRuns: 10 }); }); ``` -------------------------------- ### Install experimental fast-check with npm Source: https://fast-check.dev/docs/introduction/getting-started Install the latest experimental version of fast-check from pkg.pr.new using npm. Use with caution as APIs may be unstable. ```bash npm install --save-dev https://pkg.pr.new/fast-check@main ``` -------------------------------- ### Install experimental fast-check with pnpm Source: https://fast-check.dev/docs/introduction/getting-started Install the latest experimental version of fast-check from pkg.pr.new using pnpm. Use with caution as APIs may be unstable. ```bash pnpm add --save-dev https://pkg.pr.new/fast-check@main ``` -------------------------------- ### Replay and Shrink Reported Errors Source: https://fast-check.dev/docs/advanced/fuzzing Replay a specific failing example and attempt to shrink it by setting `numRuns` to 1 and providing the example in the `examples` option. ```javascript test('replay reported error and shrink it', () => { fc.assert(fc.property(...arbitraries, predicate), { numRuns: 1, examples: [ [ /* reported error */ ], ], }); }); ``` -------------------------------- ### Jest Setup File for Global Settings Source: https://fast-check.dev/docs/configuration/global-settings Import `fast-check` and call `configureGlobal` within the Jest setup file. ```javascript const fc = require('fast-check'); fc.configureGlobal({ numRuns: 10 }); ``` -------------------------------- ### Using Context with Custom Examples Source: https://fast-check.dev/docs/configuration/user-definable-values When using `context` for logging within a predicate, ensure your custom examples include a properly generated context instance. ```javascript const exampleContext = () => fc.sample(fc.context(), { numRuns: 1 })[0]; fc.assert(fc.property(fc.string(), fc.string(), fc.context(), myCheckFunction), { examples: [['', '', exampleContext()]], }); ``` -------------------------------- ### Define Custom Examples for One Parameter Property Source: https://fast-check.dev/docs/configuration/user-definable-values Provide a list of specific values to test against a property with a single parameter. These examples run before generated values and reduce the number of generated values tested. ```javascript fc.assert(fc.property(fc.nat(), myCheckFunction), { examples: [ [0], [Number.MAX_SAFE_INTEGER], ], }); ``` -------------------------------- ### Example usage of statistics Source: https://fast-check.dev/docs/core-blocks/runners This example shows how to use the `statistics` runner with `fc.string()`. It classifies strings by their length and runs the analysis with 100,000 iterations. ```javascript fc.statistics( fc.string(), // source arbitrary (v) => `${v.length} characters`, // classifier { numRuns: 100_000 }, // extra parameters ); // Possible output: // > 0 characters...9.65% // > 2 characters...9.56% // > 1 characters...9.41% // > 3 characters...9.30% // > 6 characters...9.04% // > 9 characters...8.92% // > 7 characters...8.90% // > 8 characters...8.90% // > 10 characters..8.86% // > 4 characters...8.79% // > 5 characters...8.68% ``` -------------------------------- ### CommonJS Module Import Example Source: https://fast-check.dev/blog/2023/09/04/dual-packages-or-supporting-both-cjs-and-esm Demonstrates how to import modules in a CommonJS (CJS) environment, typically used in Node.js. ```javascript const dep1 = require('dep1'); const dep2 = require('dep2'); ``` -------------------------------- ### Synchronous Property Example with fc.pre Source: https://fast-check.dev/docs/core-blocks/properties This example uses `fc.pre` to filter out invalid inputs (where label length exceeds maxLength) and returns a boolean to indicate success or failure. ```javascript fc.property(fc.nat(), fc.string(), (maxLength, label) => { fc.pre(label.length <= maxLength); // any label such label.length > maxLength, will be dropped return crop(label, maxLength) === label; // true is success, false is failure }); ``` -------------------------------- ### Vitest Configuration for Global Settings Source: https://fast-check.dev/docs/configuration/global-settings Configure Vitest to load global settings by specifying a setup file in `vitest.config.js`. ```javascript import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { // ... setupFiles: ['./vitest.setup.js'], }, }); ``` -------------------------------- ### Synchronous Property with Setup/Teardown Source: https://fast-check.dev/docs/core-blocks/properties Leverage `.beforeEach` and `.afterEach` to add synchronous setup and teardown logic to your properties. These hooks can call previous hooks if they exist. ```javascript fc.property(...arbitraries, (...args) => {}) .beforeEach((previousBeforeEach) => {}) .afterEach((previousAfterEach) => {}); ``` -------------------------------- ### Generated Object Examples Source: https://fast-check.dev/docs/core-blocks/arbitraries/composites/object Examples of objects generated by the configured object arbitrary, showcasing the diversity of data types and structures that can be produced. ```javascript {} ``` ```javascript {"𐝥򾫽򄓎𥸕򽊶󱂝綖":{"򉘤𿴀􀡹񻞏􃆢󂼾󺉁𤻎󁑹󩨭":"new Number(5.458711183935786e+215)","\"\"": ``` ```javascript new Set([new Number(-168580940874959),false,new String("𱚏󗿥")]) ``` ```javascript "𿚔\u0003":new Map([["󵒊󩇣󄠾󹓅",new String("􃷂󅧰􊧮򆬽尢纍񬏖򈢯")],[ "򂆶𮕉ɠ񩗢󜧡𞯧󥰆󪲳󲴥󏜠",new Number(-3.915309186966617e-201)],["񢬬󬘃񍦎𨴓򌥱򑲮󷋴󧡥󦹎񮮻",false],[ "󢎆򐵂􍨌𣏓⢋򄓢𰌂􃙼",9.778144932315068e-292],[ "󥓽򠕉",new Boolean(true)],["񳟟",new Number(7263738133547713)],["􈦶񈫡򒧯񮹡󬲒򈓠","񒂜򡌍􎅹󇤮󪶟򠿺󓸸񒴕"],["񤮇",""] ,["򰨞𧘻򪣵򄠏",new String("򿺔󴼃򷣧󓀒")]]) ``` ```javascript "򇔎󻢢򶞇񙿢񏡂󕌴񠪢𤾿򇣦􉫽":Uint8ClampedArray.from([2,167,221,250,25,5,253,3,39]) ``` ```javascript "񫍋󕪿󿫽񈬌񁷚":new Set([null,-7554992422397568,-17220778063163852213518299424149709632540904753173033601881880719429971665504n,new String(""),new Boolean(true),undefined,-10556040980590440407765974154662897970048173654375365677184296697937171159766n]) ``` ```javascript "toString":{} ``` ```javascript "񂱹":[] ``` ```javascript "𺴕󖼑򠊅𔡹򁵩":Uint8ClampedArray.from([118,211,17]) ``` ```javascript "n":"new Map([[\"",-3.847406447449319e-89]])" ``` ```javascript "\u0007\u0013򆡭\u0003諸\u0010\f":{__proto__:null,"񕯄􏿻\u000e\u0000\u000b𪲿󓕲\u0014":new Number(-7.4e-323),"󟔭򑂬𖄋񉾻𭩼𗿎򹸶臦":"", "":23060781171921571898756243128383982884697443490579335692025690551060929342872n,"u򰉠oStr":new String("򻝢󔔲𐬸򁭘񩃟򵶳񍏫𓹹򓠹򴻯"),"􏿼񺆁":null,"󅆲򚏵󪹫񌋬𮏄𚨛󉬐":new Number(-1.3004479422180178e+247)}} ``` -------------------------------- ### Example of a timeout failure report Source: https://fast-check.dev/docs/configuration/timeouts This is an example of how a timeout failure report might appear. It indicates the property failed, provides details about the seed and path, shows the counterexample, and specifies the timeout limit that was exceeded. ```text Uncaught Error: Property failed after 1 tests { seed: 1234070620, path: "0:0", endOnFailure: true } Counterexample: [new Map([["my-package",{}]]),0] Shrunk 1 time(s) Got Property timeout: exceeded limit of 1000 milliseconds Hint: Enable verbose mode in order to have the list of all failing values encountered during the run at buildError (/workspaces/fast-check/packages/fast-check/lib/check/runner/utils/RunDetailsFormatter.js:131:15) at asyncThrowIfFailed (/workspaces/fast-check/packages/fast-check/lib/check/runner/utils/RunDetailsFormatter.js:148:11) at runNextTicks (node:internal/process/task_queues:60:5) at process.processTimers (node:internal/timers:509:9) ``` -------------------------------- ### Install fast-check JavaScript Testing Expert Skill Source: https://fast-check.dev/docs/ai-powered-testing Install the fast-check skill to your AI assistant using npx. This enables the AI to apply best practices for writing high-quality JavaScript tests. ```bash npx skills add dubzzz/fast-check --skill javascript-testing-expert ``` -------------------------------- ### AMD Module Definition Example Source: https://fast-check.dev/blog/2023/09/04/dual-packages-or-supporting-both-cjs-and-esm Illustrates the syntax for defining modules using Asynchronous Module Definition (AMD), commonly used in browsers before ESM. ```javascript requirejs(['dep1', 'dep2'], function (dep1, dep2) { // This function is called when dep1.js and dep2.js // and their dependencies are loaded. }); ``` -------------------------------- ### Configure Global Settings for fast-check Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-manual-setup Use fc.configureGlobal to set shared configurations for all property-based tests. This example sets an interrupt time limit of 5000 milliseconds. ```javascript const fc = require('fast-check'); fc.configureGlobal({ interruptAfterTimeLimit: 5_000 }); ``` -------------------------------- ### Example of skipAllAfterTimeLimit usage Source: https://fast-check.dev/docs/configuration/timeouts Illustrates the output when `skipAllAfterTimeLimit` causes a failure because no predicate succeeded before the timeout. This output shows the error message, run details, and hints for debugging. ```text Failed to run property, too many pre-condition failures encountered { seed: 1119647454 } Ran 0 time(s) Skipped 10001 time(s) Hint (1): Try to reduce the number of rejected values by combining map, chain and built-in arbitraries Hint (2): Increase failure tolerance by setting maxSkipsPerRun to an higher value Hint (3): Enable verbose mode at level VeryVerbose in order to check all generated values and their associated status at buildError (/workspaces/fast-check/packages/fast-check/lib/check/runner/utils/RunDetailsFormatter.js:131:15) at asyncThrowIfFailed (/workspaces/fast-check/packages/fast-check/lib/check/runner/utils/RunDetailsFormatter.js:148:11) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) ``` -------------------------------- ### yaml: Parsing Strings Starting with ':,' Source: https://fast-check.dev/docs/introduction/track-record This example shows that the `yaml` library fails to parse string values that start with ':,'. The `stringify` function produces valid YAML, but `parse` throws a `YAMLSyntaxError`. ```javascript YAML.stringify([[':,']]); //=> '- - :,\n' YAML.parse('- - :,\n'); //=> YAMLSyntaxError: Document is not valid YAML (bad indentation?) ``` -------------------------------- ### Replace stringOf with string Source: https://fast-check.dev/docs/migration-guide/from-3.x-to-4.x Starting from v3.22.0, `stringOf` is recommended to be replaced by `string`. The example shows how to adapt the usage by passing the unit configuration to `fc.string`. ```typescript -fc.stringOf(fc.constantFrom('Hello', 'World')); +fc.string({ unit: fc.constantFrom('Hello', 'World') }); ``` -------------------------------- ### Constructor Source: https://fast-check.dev/docs/api/classes/Arbitrary Initializes a new instance of the Arbitrary class. ```APIDOC ## Constructor ### Description Initializes a new instance of the Arbitrary class. ### Signature ```typescript new Arbitrary(): Arbitrary ``` ### Returns An instance of Arbitrary. ``` -------------------------------- ### IProperty Methods Source: https://fast-check.dev/docs/api/interfaces/IProperty This section details the methods available on the IProperty interface, including generate, isAsync, run, and shrink. ```APIDOC ## generate() ### Description Generate values of type Ts. ### Parameters - **mrng** (Random) - Random number generator. - **runId?** (number) - Id of the generation, starting at 0 - if set the generation might be biased. ### Returns Value ## isAsync() ### Description Is the property asynchronous? true in case of asynchronous property, false otherwise. ### Returns false ## run() ### Description Check the predicate for v. ### Parameters - **v** (Ts) - Value of which we want to check the predicate. ### Returns PreconditionFailure | PropertyFailure | null ## shrink() ### Description Shrink value of type Ts. ### Parameters - **value** (Value) - The value to be shrunk, it can be context-less. ### Returns Stream> ``` -------------------------------- ### ModelRunAsyncSetup Source: https://fast-check.dev/docs/api/type-aliases/ModelRunAsyncSetup An asynchronous setup function that generates both the model and real representations of a value. This is useful for scenarios where you need to perform checks on both the abstract model and the concrete real value. ```APIDOC ## Type Alias: ModelRunAsyncSetup > **ModelRunAsyncSetup** <`Model`, `Real`> = () => `Promise`<{ `model`: `Model`; `real`: `Real`; }> Defined in: packages/fast-check/src/check/model/ModelRunner.ts:19 Asynchronous definition of model and real. ### Type Parameters | Type Parameter | Description | | -------------- | ----------- | | `Model` | | | `Real` | | ### Returns - `Promise`<{ `model`: `Model`; `real`: `Real`; }>: A promise that resolves to an object containing the generated model and real values. ``` -------------------------------- ### Re-run Configuration Options Source: https://fast-check.dev/docs/tutorials/quick-start/read-test-reports Details on how to use `path` and `endOnFailure` options when re-running tests. `path` starts execution on a reduced counterexample, and `endOnFailure` stops immediately on failure. ```text { seed: -1819918769, path: "0:...:3", endOnFailure: true } ``` -------------------------------- ### Shrink Custom Values for a Property Source: https://fast-check.dev/docs/configuration/user-definable-values Fast-check automatically shrinks user-defined examples if they fail, aiding in debugging. This example demonstrates shrinking a property that checks for the presence of a value in an array. ```javascript function buildQuickLookup(values) { const fastValues = Object.fromEntries(values.map((value) => [value, true])); return { has: (value) => value in fastValues }; } fc.assert( fc.property(fc.array(fc.string()), fc.string(), (allValues, lookForValue) => { const expectedResult = allValues.includes(lookForValue); const cache = buildQuickLookup(allValues); return cache.has(lookForValue) === expectedResult; }), { examples: [ [[], '__proto__'], ], }, ); ``` -------------------------------- ### EntityGraphRelations Example Source: https://fast-check.dev/docs/api/type-aliases/EntityGraphRelations This example demonstrates the structure of EntityGraphRelations, defining relationships for 'employee' and 'team' entities. The 'employee' entity has 'manager' and 'team' relationships, while 'team' has no outgoing relationships defined. ```typescript { employee: { manager: { arity: '0-1', type: 'employee' }, team: { arity: '1', type: 'team' } }, team: {} } ``` -------------------------------- ### run() Source: https://fast-check.dev/docs/api/interfaces/Command Executes the command on the system under test. It receives the non-updated model and the real system, performs post-execution checks, and throws an error if the state is invalid. It also updates the model accordingly. ```APIDOC ## run() ### Description Receive the non-updated model and the real or system under test. Perform the checks post-execution - Throw in case of invalid state. Update the model accordingly. ### Parameters #### Path Parameters - **m** (Model) - Required - Model, simplified or schematic representation of real system - **r** (Real) - Required - Sytem under test ### Returns `void` ### Remarks Since 1.5.0 ### Inherited from `ICommand`.`run` ``` -------------------------------- ### Constructor Source: https://fast-check.dev/docs/api/classes/Value Initializes a new instance of the Value class. ```APIDOC ## new Value(value_, context, customGetValue?) ### Description Initializes a new instance of the Value class. ### Parameters #### Parameters - **value_** (T) - Internal value of the shrinkable - **context** (unknown) - Context associated to the generated value (useful for shrink) - **customGetValue?** (() => T) - Limited to internal usages (to ease migration to next), it will be removed on next major ### Returns Value ``` -------------------------------- ### Run Tests with Bun Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Execute the project's tests using the Bun run test command. ```bash bun run test ``` -------------------------------- ### Run Bun Tests Source: https://fast-check.dev/docs/tutorials/setting-up-your-test-environment/property-based-testing-with-bun-test-runner Execute all tests defined in your project using the 'bun test' command in the terminal. ```bash bun test ``` -------------------------------- ### Updated entries with 'start' field for dichotomic search Source: https://fast-check.dev/blog/2024/11/05/whats-new-in-fast-check-3-23-0 Shows the internal structure of entries with the added 'start' field, enabling dichotomic search for improved performance in 'mapToConstant'. This change allows for logarithmic complexity in locating the correct 'build' function. ```javascript const entries = [ { start: 0, num: 26, build: (v) => String.fromCharCode(v + 0x61) }, { start: 26, num: 10, build: (v) => String.fromCharCode(v + 0x30) }, ]; ``` -------------------------------- ### ModelRunSetup Source: https://fast-check.dev/docs/api/type-aliases/ModelRunSetup Defines a synchronous function that returns an object containing 'model' and 'real' properties. This is used for setting up model-based property testing. ```APIDOC ## Type Alias: ModelRunSetup > **ModelRunSetup** <`Model`, `Real`> = () => `object` Defined in: packages/fast-check/src/check/model/ModelRunner.ts:12 Synchronous definition of model and real. ### Type Parameters​ Type Parameter --- `Model` `Real` ### Returns​ `object` #### model​ > **model** : `Model` #### real​ > **real** : `Real` ### Remarks​ Since 2.2.0 ``` -------------------------------- ### Filter Arbitrary for Odd Integers Source: https://fast-check.dev/docs/core-blocks/arbitraries/combiners/any This example demonstrates filtering for odd integers, showing the flexibility of the .filter combinator. ```javascript fc.integer().filter((n) => n % 2 !== 0); ``` -------------------------------- ### sample() Source: https://fast-check.dev/docs/api/functions/sample Generates an array containing all the values that would have been generated during assert or check. ```APIDOC ## Function: sample() > **sample** <`Ts`>(`generator`, `params?`): `Ts`[] Defined in: packages/fast-check/src/check/runner/Sampler.ts:62 Generate an array containing all the values that would have been generated during assert or check ## Type Parameters​ Type Parameter --- `Ts` ## Parameters​ Parameter| Type| Description ---|---|--- `generator`| `IRawProperty`<`Ts`, `boolean`> | `Arbitrary`<`Ts`>| IProperty or Arbitrary to extract the values from `params?`| `number` | `Parameters`<`Ts`>| Integer representing the number of values to generate or `Parameters` as in assert ## Returns​ `Ts`[] ## Example​ ```typescript fc.sample(fc.nat(), 10); // extract 10 values from fc.nat() Arbitrary fc.sample(fc.nat(), {seed: 42}); // extract values from fc.nat() as if we were running fc.assert with seed=42 ``` ## Remarks​ Since 0.0.6 ``` -------------------------------- ### Generate Boolean Values Source: https://fast-check.dev/docs/core-blocks/arbitraries/primitives/boolean Use `fc.boolean()` to generate random boolean values. Examples include `true` and `false`. ```javascript fc.boolean(); // Examples of generated values: true, false… ``` -------------------------------- ### Run Tests with npm Source: https://fast-check.dev/docs/tutorials/quick-start/basic-setup Execute the project's tests using the npm test script. ```bash npm test ``` -------------------------------- ### Root package.json for Dual Module Support Source: https://fast-check.dev/blog/2023/09/04/dual-packages-or-supporting-both-cjs-and-esm Configure the root package.json with 'main' for CJS, 'module' for ESM, and the 'exports' field to define entry points for both module systems, including type definitions. ```json { "type": "commonjs", "main": "lib/fast-check.js", "module": "lib/esm/fast-check.js", "exports": { "./package.json": "./package.json", ".": { "require": { "types": "./lib/fast-check.d.ts", "default": "./lib/fast-check.js" }, "import": { "types": "./lib/esm/fast-check.d.ts", "default": "./lib/esm/fast-check.js" } } }, "types": "lib/fast-check.d.ts" } ``` -------------------------------- ### Jest Configuration for Global Settings Source: https://fast-check.dev/docs/configuration/global-settings Configure Jest to load global settings by specifying a setup file in `jest.config.js`. ```javascript module.exports = { setupFiles: ['./jest.setup.js'], }; ``` -------------------------------- ### Map Arbitrary to Square Values Source: https://fast-check.dev/docs/core-blocks/arbitraries/combiners/any Use .map to transform generated values. This example maps natural numbers to their squares. ```javascript fc.nat(1024).map((n) => n * n); ``` -------------------------------- ### Generate ULID using fast-check Source: https://fast-check.dev/blog/2023/06/07/whats-new-in-fast-check-3-11-0 Use the `ulid` arbitrary to generate ULID strings. Examples of generated values are provided. ```javascript fc.ulid(); // Examples of generated values: // • "7AVDFZJAXCM0F25E3SZZZZZZYZ" // • "7ZZZZZZZYP5XN60H51ZZZZZZZP" // • "2VXXEMQ2HWRSNWMP9PZZZZZZZA" // • "15RQ23H1M8YB80EVPD2EG8W7K1" // • "6QV4RKC7C8ZZZZZZZFSF7PWQF5" // • … ``` -------------------------------- ### modelRun() Source: https://fast-check.dev/docs/api/functions/modelRun Runs synchronous commands over a Model and the Real system. Throws in case of inconsistency. ```APIDOC ## Function: modelRun() > **modelRun** <`Model`, `Real`, `InitialModel`>(`s`, `cmds`): `void` Defined in: packages/fast-check/src/check/model/ModelRunner.ts:113 Run synchronous commands over a `Model` and the `Real` system Throw in case of inconsistency ## Type Parameters | Type Parameter | Description | |---|---| | `Model` _extends_ `object` | | `Real` | | `InitialModel` _extends_ `object` | ## Parameters | Parameter | Type | Description | |---|---|---| | `s` | `ModelRunSetup`<`InitialModel`, `Real`> | Initial state provider | | `cmds` | `Iterable`<`Command`<`Model`, `Real`>> | Synchronous commands to be executed | ## Returns `void` ## Remarks Since 1.5.0 ``` -------------------------------- ### Map Arbitrary to String Type Source: https://fast-check.dev/docs/core-blocks/arbitraries/combiners/any Transform the type of generated values using .map. This example converts natural numbers to strings. ```javascript fc.nat().map((n) => String(n)); ``` -------------------------------- ### asyncProperty() Source: https://fast-check.dev/docs/api/functions/asyncProperty Instantiate a new fast-check#IAsyncProperty. ```APIDOC ## Function: asyncProperty() > **asyncProperty** <`Ts`>(...`args`): `IAsyncPropertyWithHooks`<`Ts`> Defined in: packages/fast-check/src/check/property/AsyncProperty.ts:15 Instantiate a new fast-check#IAsyncProperty. ## Type Parameters​ Type Parameter --- `Ts` _extends_ [`unknown`, `...unknown[]`] ## Parameters​ Parameter| Type --|-- ...`args`| [...arbitraries: { [K in string | number | symbol]: Arbitrary }[], (...`args`) => `Promise`<`boolean` | `void`>] ## Returns​ `IAsyncPropertyWithHooks`<`Ts`> ## Remarks​ Since 0.0.7 ``` -------------------------------- ### Random User Test Source: https://fast-check.dev/docs/advanced/fake-data Example of a traditional random test generating user data. This approach lacks reproducibility and shrinking capabilities. ```javascript test('sort users by ascending age', () => { const userA = { firstName: firstName(), lastName: lastName(), birthDate: birthDate(), }; const userB = { firstName: firstName(), lastName: lastName(), birthDate: birthDate({ strictlyOlderThan: userA.birthDate }), }; expect(sortByAge([userA, userB])).toEqual([userA, userB]); expect(sortByAge([userB, userA])).toEqual([userA, userB]); }); ``` -------------------------------- ### anything(constraints) Source: https://fast-check.dev/docs/api/functions/anything Generates arbitrary values of any type following the specified constraints. You can use sample() to preview the generated values. ```APIDOC ## anything(constraints) ### Description Generates arbitrary values of any type following the constraints defined by `settings`. ### Parameters #### Parameters - **constraints** (`ObjectConstraints`) - Constraints to apply when building instances ### Returns `Arbitrary` ### Examples ``` // Using custom settings fc.anything({ key: fc.string(), values: [fc.integer(10,20), fc.constant(42)], maxDepth: 2 }); // Can build entries such as: // - 19 // - [{"2":12,"k":15,"A":42}] // - {"4":[19,13,14,14,42,11,20,11],"6":42,"7":16,"L":10,"'":[20,11],"e":[42,20,42,14,13,17]} // - [42,42,42]... ``` ### Remarks Since 0.0.7 ``` -------------------------------- ### Example Test Failure Report Source: https://fast-check.dev/docs/tutorials/quick-start/read-test-reports A typical test failure report from fast-check, indicating a property failure with a specific seed, path, and counterexample. ```text **FAIL** sort.test.mjs > should sort numeric elements from the smallest to the largest one Error: Property failed after 1 tests { seed: -1819918769, path: "0:...:3", endOnFailure: true } Counterexample: [[2,1000000000]] Shrunk 66 time(s) Got error: AssertionError: expected 1000000000 to be less than or equal to 2 ``` -------------------------------- ### Generate Tuple with Multiple Arbitraries Source: https://fast-check.dev/docs/core-blocks/arbitraries/composites/array Use fc.tuple with multiple arbitraries to generate arrays with elements corresponding to each arbitrary. Examples show generated values. ```javascript fc.tuple(fc.nat(), fc.string()); // Examples of generated values: [17,"n"], [1187149108,"{}"], [302474255,"!!]"], [2147483618,"$"], [21,"lv V!""]… ``` -------------------------------- ### Basic fast-check property test Source: https://fast-check.dev/docs/introduction/getting-started Demonstrates how to import fast-check and define simple properties for testing. The `fc.assert` runner executes the property, attempting to shrink failures to minimal examples. ```javascript import fc from 'fast-check'; // Code under test const contains = (text, pattern) => text.indexOf(pattern) >= 0; // Properties describe('properties', () => { // string text always contains itself it('should always contain itself', () => { fc.assert( fc.property(fc.string(), (text) => { return contains(text, text); }), ); }); // string a + b + c always contains b, whatever the values of a, b and c it('should always contain its substrings', () => { fc.assert( fc.property(fc.string(), fc.string(), fc.string(), (a, b, c) => { // Alternatively: no return statement and direct usage of expect or assert return contains(a + b + c, b); }), ); }); }); ``` -------------------------------- ### Generate Tuple with Single Arbitrary Source: https://fast-check.dev/docs/core-blocks/arbitraries/composites/array Use fc.tuple with a single arbitrary to generate arrays containing one element. Examples show generated values. ```javascript fc.tuple(fc.nat()); // Examples of generated values: [15], [1564085383], [2147483642], [1564562962], [891386821]… ``` -------------------------------- ### Map String to Formatted String Source: https://fast-check.dev/docs/core-blocks/arbitraries/combiners/any Transform a generated string into a new formatted string using .map. This example prepends the string's length. ```javascript fc.string().map((s) => `[${s.length}] -> ${s}`); ```