Search
⌘K

Vitest Utils

Utilities for working with vitest.

Example Usage

repeatSyncFn

Use this function to repeat a sync function a certain number of times.

import { it, expect } from 'vitest';
import { repeatSyncFn } from './vitest.utils';

// repeatSyncFn
it('use repeatSyncFn', () => {
  repeatSyncFn(10_000, () => {
    expect(true).toBe(true);
  });
}))

repeatAsyncFn

Use this function to repeat an async function a certain number of times.

Internally this uses Promise.all.

import { it, expect } from 'vitest';
import { repeatAsyncFn } from './vitest.utils';

// when you don't care about the return value
it('use repeatAsyncFn', async () => {
  await repeatAsyncFn(10_000, async () => {
    expect(true).toBe(true);
  })
});

// when you care about the return value
it('use repeatAsyncFn', async () => {
  const result = await repeatAsyncFn(10_000, async () => {
    if (Math.random() > 0.5) return true;
    return false;
  });
  expect(Array.isArray(result)).toBe(true);
  result.forEach((item) => expect(item).oneOf([true, false]))
})

Dependencies

npmvitest

Auto Install

npx shadcn@latest add https://shadcn-registry-ts.vercel.app/r/util-vitest-utils.json

Manual Install

vitest.utils.ts
/**
 * Repeat a `sync` function a number of times.  
 * For async fn use {@link repeatAsyncFnInParallel}
 */
export function repeatSyncFn(
  /** how many times to repeat? */
  times: number,
  /** function to repeat */
  fn: () => void,
) {
  for (let i = 0; i < times; i++) {
    fn();
  }
};

/**
 * Repeat an `async` function a number of times.  
 * For sync fn use {@link repeatSyncFn}
 */
export async function repeatAsyncFnInParallel<TReturn>(
  /** how many times to repeat? */
  times: number,
  /** function to repeat. */
  fn: () => Promise<TReturn>
) {
  return Promise.all(
    Array.from({ length: times }, fn)
  );
}

Test

No test

Command Palette

Search for a command to run...