Best JavaScript code snippet using fast-check-monorepo
AsyncScheduler.spec.ts
Source:AsyncScheduler.spec.ts
1import fc from '../../src/fast-check';2import { seed } from './seed';3describe(`AsyncScheduler (seed: ${seed})`, () => {4 it('should detect trivial race conditions', async () => {5 // The code below relies on the fact/expectation that fetchA takes less time that fetchB6 // The aim of this test is to show that the code is wrong as soon as this assumption breaks7 type CompoProps = { fetchHeroName: () => Promise<string>; fetchHeroes: () => Promise<{ name: string }[]> };8 type CompoState = { heroName: string | undefined; heroes: { name: string }[] | undefined };9 class Compo {10 private props: CompoProps;11 private state: CompoState;12 constructor(props: CompoProps) {13 this.props = props;14 this.state = { heroName: undefined, heroes: undefined };15 }16 componentDidMount() {17 this.props.fetchHeroName().then((heroName) => (this.state = { ...this.state, heroName }));18 this.props.fetchHeroes().then((heroes) => (this.state = { ...this.state, heroes }));19 }20 render() {21 const { heroName, heroes } = this.state;22 if (!heroes) return null;23 return `got: ${heroes.find((h) => h.name === heroName!.toLowerCase())}`;24 }25 }26 const out = await fc.check(27 fc.asyncProperty(fc.scheduler(), async (s) => {28 const fetchHeroName = s.scheduleFunction(function fetchHeroName() {29 return Promise.resolve('James Bond');30 });31 const fetchHeroes = s.scheduleFunction(function fetchHeroesById() {32 return Promise.resolve([{ name: 'James Bond' }]);33 });34 const c = new Compo({ fetchHeroName, fetchHeroes });35 c.componentDidMount();36 c.render();37 while (s.count() !== 0) {38 await s.waitOne();39 c.render();40 }41 }),42 { seed }43 );44 expect(out.failed).toBe(true);45 expect(out.counterexample![0].toString()).toEqual(46 'schedulerFor()`\n' +47 '-> [task${2}] function::fetchHeroesById() resolved with value [{"name":"James Bond"}]\n' +48 '-> [task${1}] function::fetchHeroName() pending`'49 );50 // Node <16: Cannot read property 'toLowerCase' of undefined51 // Node >=16: TypeError: Cannot read properties of undefined (reading 'toLowerCase')52 expect(out.error).toContain(`'toLowerCase'`);53 });54 it('should detect race conditions leading to infinite loops', async () => {55 // Following case is an example of code trying to scan all the dependencies of a given package56 // In order to build a nice graph57 type PackageDefinition = {58 dependencies: { [packageName: string]: string };59 };60 type AllPackagesDefinition = { [packageName: string]: PackageDefinition };61 const allPackages: AllPackagesDefinition = {62 toto: {63 dependencies: {64 titi: '^1.0.0',65 tata: '^2.0.0',66 tutu: '^3.0.0',67 },68 },69 titi: {70 dependencies: {71 noop: '^1.0.0',72 tutu: '^3.0.0',73 },74 },75 tata: {76 dependencies: {77 noop: '^1.0.0',78 },79 },80 noop: {81 dependencies: {},82 },83 tutu: {84 dependencies: {85 titi: '^1.0.0',86 },87 },88 };89 const buildGraph = async (90 initialPackageName: string,91 fetch: (packageName: string) => Promise<PackageDefinition>92 ) => {93 const cache: AllPackagesDefinition = {};94 // // Uncomment to remove the bug95 //const cachePending = new Set<string>();96 const feedCache = async (packageName: string) => {97 // // Uncomment to remove the bug98 // if (cachePending.has(packageName)) return;99 // cachePending.add(packageName);100 if (cache[packageName]) return;101 const packageDef = await fetch(packageName); // cache miss102 // eslint-disable-next-line require-atomic-updates103 cache[packageName] = packageDef;104 await Promise.all(Object.keys(packageDef.dependencies).map((dependencyName) => feedCache(dependencyName)));105 };106 await feedCache(initialPackageName);107 return cache; // we just return the cache instead of the garph for simplicity108 };109 const out = await fc.check(110 fc.asyncProperty(fc.constantFrom(...Object.keys(allPackages)), fc.scheduler(), async (initialPackageName, s) => {111 let numFetches = 0;112 const originalFetch = (packageName: string) => {113 ++numFetches;114 return Promise.resolve(allPackages[packageName]);115 };116 const fetch = s.scheduleFunction(originalFetch);117 const handle = buildGraph(initialPackageName, fetch);118 // Or: await s.waitAll();119 while (s.count() !== 0) {120 expect(numFetches).toBeLessThanOrEqual(Object.keys(allPackages).length);121 await s.waitOne();122 }123 await handle; // nothing should block now124 }),125 { seed }126 );127 expect(out.failed).toBe(true);128 });129 it('should be able to replay failures using examples and the value of schedulerFor extracted from error logs', async () => {130 const inc = async (db: { read: () => Promise<number>; write: (n: number) => Promise<void> }) => {131 const v = await db.read();132 await db.write(v + 1);133 };134 const propertyValidator = async (s: fc.Scheduler) => {135 let value = 0;136 const db = {137 read: s.scheduleFunction(async function read() {138 return value;139 }),140 write: s.scheduleFunction(async function write(n: number) {141 value = n;142 }),143 };144 s.schedule(Promise.resolve('A')).then(() => inc(db));145 s.schedule(Promise.resolve('B')).then(() => inc(db));146 s.schedule(Promise.resolve('C')).then(() => inc(db));147 await s.waitAll();148 expect(value).toBe(3);149 };150 const out = await fc.check(fc.asyncProperty(fc.scheduler(), propertyValidator));151 expect(out.failed).toBe(true);152 const schedulerTemplatedString = String(out.counterexample![0]);153 const argsForSchedulerFor: any[] = eval(`(() => {154 // Extract template string parameters155 function schedulerFor() {156 return function(strs, ...ordering) {157 return [strs, ...ordering];158 }159 }160 return ${schedulerTemplatedString};161 })()`);162 const outRetry = await fc.check(fc.asyncProperty(fc.scheduler(), propertyValidator), {163 examples: [[(fc.schedulerFor() as any)(...argsForSchedulerFor)]],164 });165 expect(outRetry.failed).toBe(true);166 expect(outRetry.numRuns).toBe(1);167 const cleanError = (error: string) => {168 return error.replace(/AsyncScheduler\.spec\.ts:\d+:\d+/g, 'AsyncScheduler.spec.ts:*:*');169 };170 expect(cleanError(outRetry.error!)).toBe(cleanError(out.error!));171 expect(String(outRetry.counterexample![0])).toBe(String(out.counterexample![0]));172 });...
Using AI Code Generation
1const { schedulerTemplatedString } = require('fast-check-monorepo');2console.log(schedulerTemplatedString());3const { schedulerTemplatedString } = require('fast-check-monorepo');4console.log(schedulerTemplatedString());5const { schedulerTemplatedString } = require('fast-check-monorepo');6console.log(schedulerTemplatedString());7const { schedulerTemplatedString } = require('fast-check-monorepo');8console.log(schedulerTemplatedString());9const { schedulerTemplatedString } = require('fast-check-monorepo');10console.log(schedulerTemplatedString());11const { schedulerTemplatedString } = require('fast-check-monorepo');12console.log(schedulerTemplatedString());13const { schedulerTemplatedString } = require('fast-check-monorepo');14console.log(schedulerTemplatedString());
Using AI Code Generation
1const { schedulerTemplatedString } = require('fast-check');2const { scheduler } = require('rxjs');3const { TestScheduler } = require('rxjs/testing');4const testScheduler = new TestScheduler((actual, expected) => {5 expect(actual).toEqual(expected);6});7const run = () => {8 testScheduler.run(({ cold, expectObservable }) => {9 const values = { a: 1, b: 2, c: 3 };10 const source$ = cold('-a-b-c-|', values);11 const expected$ = cold('-a-b-c-|', values);12 expectObservable(source$).toBe('-a-b-c-|', values);13 });14};15run();16 ✕ rxjs (3 ms)17 - Object {18 - "notification": Object {19 - },20 - },21 - Object {22 - "notification": Object {23 - },24 - },25 - Object {26 - "notification": Object {27 - },28 - },29 - Object {30 - "notification": Object {31 - },32 - },33 + Object {34 + "notification": Object {35 + },36 + },37 + Object {
Using AI Code Generation
1const { schedulerTemplatedString } = require("fast-check");2const { scheduler } = require("@most/scheduler");3const { runEffects, tap } = require("@most/core");4const { newDefaultScheduler } = require("@most/scheduler");5const { periodic } = require("@most/core");6const { take } = require("@most/core");7const { observe } = require("@most/core");8const { map } = require("@most/core");9const { chain } = require("@most/core");10const { ap } = require("@most/core");11const { mergeArray } = require("@most/core");12const { merge } = require("@most/core");13const { of } = require("@most/core");14const { scan } = require("@most/core");15const { join } = require("@most/core");16const { startWith } = require("@most/core");17const { switchLatest } = require("@most/core");18const { continueWith } = require("@most/core");19const { concat } = require("@most/core");20const { filter } = require("@most/core");21const { skipRepeats } = require("@most/core");22const { skip } = require("@most/core");23const { skipUntil } = require("@most/core");24const { skipWhile } = require("@most/core");25const { takeUntil } = require("@most/core");26const { takeWhile } = require("@most/core");27const { until } = require("@most/core");28const { withLatestFrom } = require("@most/core");29const { sample } = require("@most/core");30const { fromPromise } = require("@most/core");31const { fromEvent } = require("@most/core");32const { unfold } = require("@most/core");33const { iterate } = require("@most/core");34const { generate } = require("@most/core");35const { throwError } = require("@most/core");36const { empty } = require("@most/core");37const { never } = require("@most/core");38const { from } = require("@most/core");39const { run } = require("@most/core");40const { Stream } = require("@most/types");41const { Scheduler } = require("@most/types");42const { Disposable } = require("@most/types");43const { Sink } = require("@most/types");44const { Time } = require("@most/types");45const { PropagateTask } = require("@most/types");46const { ScheduledTask } = require("@most/types");47const { Task } = require("@most/types");
Using AI Code Generation
1const { schedulerTemplatedString } = require('fast-check-monorepo');2const { scheduler } = require('fast-check/scheduler/Scheduler');3const { run } = require('fast-check/scheduler/Runner');4const result = run(scheduler, schedulerTemplatedString('Hello World'));5const { schedulerTemplatedString } = require('fast-check-monorepo');6const { scheduler } = require('fast-check/scheduler/Scheduler');7const { run } = require('fast-check/scheduler/Runner');8const result = run(scheduler, schedulerTemplatedString('Hello World'));9const { schedulerTemplatedString } = require('fast-check-monorepo');10const { scheduler } = require('fast-check/scheduler/Scheduler');11const { run } = require('fast-check/scheduler/Runner');12const result = run(scheduler, schedulerTemplatedString('Hello World'));13const { schedulerTemplatedString } = require('fast-check-monorepo');14const { scheduler } = require('fast-check/scheduler/Scheduler');15const { run } = require('fast-check/scheduler/Runner');16const result = run(scheduler, schedulerTemplatedString('Hello World'));17const { schedulerTemplatedString } = require('fast-check-monorepo');18const { scheduler } = require('fast-check/scheduler/Scheduler');19const { run } = require('fast-check/scheduler/Runner');20const result = run(scheduler, schedulerTemplatedString('Hello World'));21const { schedulerTemplatedString } = require('fast-check-monorepo');22const { scheduler } = require('fast-check/scheduler/Scheduler');23const {
Using AI Code Generation
1import { schedulerTemplatedString } from 'fast-check-monorepo';2import { run } from 'rxjs-marbles/jest';3import { map } from 'rxjs/operators';4const scheduler = schedulerTemplatedString`--a--b--c--d--e--f--g--h--i--j--|`;5const expected = schedulerTemplatedString`--a--b--c--d--e--f--g--h--i--j--|`;6const source = schedulerTemplatedString`-a-b-c-d-e-f-g-h-i-j-|`;7run(({ cold, expectObservable }) => {8 const input$ = cold(source);9 const result$ = input$.pipe(map((x) => x));10 expectObservable(result$).toBe(expected);11}, { scheduler });12function schedulerTemplatedString(13): string;14import { schedulerTemplatedString } from 'fast-check-monorepo';15import { run } from 'rxjs-marbles/jest';16import { map } from 'rxjs/operators';17const scheduler = schedulerTemplatedString`--a--b--c--d--e--f--g--h--i--j--|`;18const expected = schedulerTemplatedString`--a--b--c--d--e--f--g--h--i--j--|`;19const source = schedulerTemplatedString`-a-b-c-d-e-f-g-h-i-j-|`;20run(({ cold, expectObservable }) => {21 const input$ = cold(source);22 const result$ = input$.pipe(map((x) => x));23 expectObservable(result$).toBe(expected
Using AI Code Generation
1const fs = require('fs');2const fastCheck = require('fast-check');3const { schedulerTemplatedString } = require('fast-check-monorepo/test/unit/check/arbitrary/AsyncSchedulerArbitrary.spec.ts');4const testCases = schedulerTemplatedString().generate(fastCheck.mutable.string()).value;5const fs = require('fs');6const fastCheck = require('fast-check');7const { schedulerTemplatedString } = require('fast-check-monorepo/test/unit/check/arbitrary/AsyncSchedulerArbitrary.spec.ts');8const testCases = schedulerTemplatedString().generate(fastCheck.mutable.string()).value;9const fs = require('fs');10const fastCheck = require('fast-check');11const { schedulerTemplatedString } = require('fast-check-monorepo/test/unit/check/arbitrary/AsyncSchedulerArbitrary.spec.ts');12const testCases = schedulerTemplatedString().generate(fastCheck.mutable.string()).value;13const fs = require('fs');14const fastCheck = require('fast-check');15const { schedulerTemplatedString } = require('fast-check-monorepo/test/unit/check/arbitrary/AsyncSchedulerArbitrary.spec.ts');16const testCases = schedulerTemplatedString().generate(fastCheck.mutable.string()).value;17const fs = require('fs');18const fastCheck = require('fast-check');19const { schedulerTemplatedString } = require('fast-check-monorepo/test
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!!