Testing

Empty the resource cache between tests, and drive the timers and the network state from a test.

On this page

The resource cache

ts
import { resetResources } from '@k8ordo/effects/testing';
import { afterEach } from 'vitest';

afterEach(() => {
  resetResources();
});

A resource keeps what it loaded for the life of the page, which in a test run means across tests. resetResources() empties every resource’s cache, so the next read loads again.

Call it between tests that read the same resource. It comes from @k8ordo/effects/testing, the entry for tests.

The other hooks

The other hooks keep nothing between tests: their listeners, channels and timers go when the component unmounts.

Timers

ts
import { afterEach, beforeEach, vi } from 'vitest';

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  vi.useRealTimers();
});

Vitest’s fake timers drive the delays of useInterval, useTimeout and usePolling. Advance them with vi.advanceTimersByTime(), and the callbacks due in that time run.

poll returns a promise, so advance usePolling with vi.advanceTimersByTimeAsync(), which lets promises settle as it goes.

Going offline

ts
import { afterEach } from 'vitest';

const goOffline = () => {
  Object.defineProperty(navigator, 'onLine', {
    configurable: true,
    get: () => false,
  });
  window.dispatchEvent(new Event('offline'));
};

afterEach(() => {
  Reflect.deleteProperty(navigator, 'onLine');
});

A browser test cannot take the network away. To test useOnline, define navigator.onLine and dispatch the offline event.

After each test, delete the property to get the real navigator.onLine back.

k8ordo

React libraries that use Baseline features without holding back.