For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/testing-library/fakes/sensors.md.

Sensor and audio fakes

Put the phone somewhere, tilt it, ask for Face ID, record audio or play it in a unit test. import { setLocation, emitMotion } from '@blotch/angular-lynx-testing-library';

Location

Fakes the phone behind LynxGeolocation. Each test starts with permission unknown, not allowed all the time, and no location. It acts as an app with backgroundLocation and permissions.locationAlways, so a background watch runs as any other, and areas work.

setLocationPermission('precise');
setLocation({ latitude: 51.5007, longitude: -0.1246 });
await render(Nearby);

expect(await screen.findByText('2 shops near you')).toBeInTheDocument();

setLocation()

function setLocation(location: FakeLocation | null): void;

type FakeLocation = {
  readonly latitude: number;
  readonly longitude: number;
  readonly accuracy?: number; // meters, 5 by default
  readonly altitude?: number | null;
  readonly altitudeAccuracy?: number | null;
  readonly heading?: number | null;
  readonly speed?: number | null;
  readonly timestamp?: number; // ms since 1970, now by default
};

Puts the phone at location. It's what getCurrentPosition() resolves with, and the next position each running watch gets.

  • A watch skips it when it's nearer the last one than the watch's distanceFilter.
  • An area watchRegion() watches hears enter when it takes the phone into it, and exit when it takes it out. An area started with the phone inside hears enter at once.
  • Only latitude and longitude are needed. accuracy is 5 meters and timestamp now, unless you give them.
  • Until a spec sets one, or after null, the phone can't find itself. getCurrentPosition() rejects with timeout.

setLocationPermission()

function setLocationPermission(
  permission: 'unknown' | 'denied' | 'approximate' | 'precise',
): void;

Sets what the app is allowed, as if the person had answered the prompt or changed it in Settings. It's what state() reports.

  • At unknown, the first call that needs the location shows the prompt.
  • denied ends every running watch with denied, as it does on a phone.
  • Anything but precise ends every area with denied, since areas need the precise location.

setLocationAlways()

function setLocationAlways(allowed: boolean): void;

Sets whether the app may find the phone all the time, as if the person had chosen in Settings. It's what always() reports while the location is allowed. false ends every area with denied.

setLocationPermission('precise');
setLocationAlways(true);
setLocation({ latitude: 51.5007, longitude: -0.1246 });
await render(ShopArrival);

expect(await screen.findByText("You're at the shop")).toBeInTheDocument();

setLocationAnswer()

function setLocationAnswer(answer: 'denied' | 'approximate' | 'precise'): void;

What the person answers when the prompt shows: precise by default. The prompt shows only while the permission is unknown.

setLocationAlwaysAnswer()

function setLocationAlwaysAnswer(allowed: boolean): void;

What the person answers when requestPermission({ always: true }) or watchRegion() asks for the location all the time: true (allow it) by default. It asks once, after the location prompt if that shows too, as iOS does, and not after setLocationAlways().

setLocationEnabled()

function setLocationEnabled(enabled: boolean): void;

Turns Location on or off for the whole phone. Off, state() is off whatever the app is allowed. Calls reject with off, and every running watch and area ends with off.

locationPrompts()

function locationPrompts(): number;

How many times a location prompt showed in this test, the one for the location all the time included. A spec can check the app asks at the right moment, and only once. Each test starts at 0.

Motion

Stands in for a phone with every sensor, for LynxMotion. Each function sends what the iOS and Android apps send, through the background thread. Wait for it with waitForUpdate().

await render(Level);
emitMotion({ orientation: { alpha: 0, beta: 0, gamma: 12 } });
shakeDevice();
await waitForUpdate();

expect(screen.getByText('12°')).toBeInTheDocument();

A sensor nothing watches isn't running, so nothing reaches the app, as on a phone.

emitMotion()

function emitMotion(motion: EmittedMotion): void;

type EmittedMotion = {
  acceleration?: { x: number; y: number; z: number }; // m/s², with gravity
  rotation?: { x: number; y: number; z: number }; // rad/s
  orientation?: { alpha: number; beta: number; gamma: number }; // degrees
  timestamp?: number;
};

Sends a sample to the app's watchAcceleration(), watchRotation() and watchOrientation() watches.

setHeading()

function setHeading(heading: number | EmittedHeading): void;

type EmittedHeading = {
  magneticHeading: number;
  trueHeading?: number | null;
  accuracy?: number | null;
  timestamp?: number;
};

Sends a compass heading to the app's watchHeading() watches: degrees from magnetic north, or an object with the true heading and accuracy too.

shakeDevice()

function shakeDevice(): void;

Runs the app's onShake() handlers, the ones listening when it's called.

Sample timestamps

  • A sample without a timestamp counts as a second after the latest one sent, of any sensor, or now, if that's later. So a watch whose interval is a second or less gets it at once.
  • A sample with one is stamped as given. Each watch is spaced by its own interval, as on a phone: a sample stamped closer to the last one the watch got than its interval is held back.
  • A held sample arrives an interval later, by the timers, unless a newer sample comes first. With 1000 and then 1050, a 100 ms watch gets the first at once and the second 100 ms later. Advance fake timers to see it, or stamp samples at least a watch's interval apart.

Biometrics

Fakes the phone behind LynxBiometrics and LynxSecureStorage's requireBiometrics. They see it as they see the native module on a phone.

Each test starts with a phone that has Face ID set up behind a passcode, where every prompt succeeds.

await render(Unlock);
queueBiometricResult('canceled');

fireEvent.tap(screen.getByText('Unlock'));
await waitForUpdate();

expect(screen.getByText('Still locked')).toBeInTheDocument();
expect(biometricPrompts()).toEqual([
  { reason: 'Unlock your notes', allowDeviceCredential: false },
]);

setBiometrics()

function setBiometrics(phone: {
  readonly type?: BiometryType;
  readonly enrolled?: boolean;
  readonly deviceCredential?: boolean;
}): void;

Changes the phone. What you leave out keeps its value. { type: 'none' } is a phone without a sensor, or an app without permissions.biometrics.

queueBiometricResult()

function queueBiometricResult(result: 'success' | BiometricsErrorCode): void;

Has the next prompt end that way, such as 'canceled'. Results queue one per prompt. Once they run out, prompts succeed.

biometricPrompts()

function biometricPrompts(): readonly {
  readonly reason: string;
  readonly allowDeviceCredential: boolean;
}[];

Lists the prompts the app showed, oldest first: each authenticate(), and each read of a value kept behind biometrics.

Audio recorder

Fakes LynxAudioRecorder's native module. Each test starts with a person who hasn't been asked for the microphone: the first start() asks, and they allow it.

setRecordedAudio({ bytes: new Uint8Array([1, 2, 3]), durationMs: 4200 });
await render(VoiceNote);
fireEvent.tap(screen.getByText('Record'));
await waitForUpdate();
emitAudioLevel(0.5);
fireEvent.tap(screen.getByText('Send'));
await waitForUpdate();

expect(screen.getByText('Sending 4 s')).toBeInTheDocument();

setMicrophonePermission()

function setMicrophonePermission(
  permission: 'granted' | 'denied' | 'undetermined' | 'unsupported',
): void;

Sets what the person answered. denied has start() reject with denied, and unsupported with unavailable.

Set it before rendering: permission() reads it at startup, and each time the app comes back.

setRecordedAudio()

function setRecordedAudio(audio: FakeRecordedAudio): void;

Sets what the clips hold:

  • bytes: what blob() resolves with.
  • mimeType: audio/mp4 by default.
  • durationMs: without it, a clip is as long as it recorded by the clock, pauses left out. vi.useFakeTimers() moves that clock.

clip.delete() deletes the fake phone's file, as a phone does, and blob() rejects after it.

emitAudioLevel()

function emitAudioLevel(level: number): void;

Sends the open recording's level, from 0 to 1, as a phone does about ten times a second. Once the recording is as long as its maxDuration, it ends instead, and stop() resolves with the clip.

interruptAudioRecording()

function interruptAudioRecording(): void;

Pauses the recording, as a phone call or going to the background does.

failAudioRecording()

function failAudioRecording(message?: string): void;

Ends the recording with a failed error, which stop() rejects with.

audioRecording()

function audioRecording(): FakeAudioRecordingInfo | undefined;

Says what's open: its state (recording or paused) and maxDuration.

Audio player

Fakes LynxAudioPlayer's native module. A track loads at once, a minute long unless the track or setAudioFile() says, and plays by the clock: its position moves with fake timers, and the module sends it four times a second, as a phone does, until it ends.

Fake Date and the intervals, and leave the frames change detection waits for on the real clock:

vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });
setAudioFile('https://example.com/episodes/42.mp3', { duration: 1800 });
await render(Episode);
fireEvent.tap(screen.getByText('Play'));
await waitForUpdate();
vi.advanceTimersByTime(10_000);
await waitForUpdate();

expect(audioPlayback()?.position).toBe(10);
pressRemoteCommand('next');
await waitForUpdate();
expect(audioPlayback()?.track.title).toBe('Episode 43');

setAudioFile()

function setAudioFile(url: string, file: FakeAudioFile): void;

Sets what the phone finds at url:

  • duration: how long it plays, in seconds.
  • error: why it won't load: network, unsupported-format or failed. load() rejects with it.

audioPlayback()

function audioPlayback(): FakeAudioPlaybackInfo | undefined;

Says what's loaded, or undefined before load() and after stop(): its state (playing, paused or ended), position and duration in seconds, the track the lock screen shows, and the remoteCommands the app takes with onRemoteCommand().

pressRemoteCommand()

function pressRemoteCommand(
  command: 'play' | 'pause' | 'next' | 'previous' | 'seek',
  position?: number,
): void;

Presses a lock-screen button, as a phone hears it: a command the app takes goes to its handler, and play, pause and seek act on the player otherwise. position is where the slider was moved to, for seek. It throws for next or previous while the app doesn't take them, since the lock screen doesn't show them then, and with nothing loaded.

interruptAudioPlayback()

function interruptAudioPlayback(): void;

Pauses the track, as a phone call does.

failAudioPlayback()

function failAudioPlayback(
  code?: 'network' | 'unsupported-format' | 'failed',
  message?: string,
): void;

Stops the track with an error, as a dropped connection does: state turns error, and error() holds the AudioPlayerError. network by default.

Types

TypeDescription
FakeLocationWhat setLocation() takes
FakeLocationPermissionWhat setLocationPermission() takes
EmittedMotionWhat emitMotion() takes
EmittedHeadingWhat setHeading() takes, besides a number
MotionVectorThe { x, y, z } of acceleration and rotation
FakeBiometricsWhat setBiometrics() takes: type (faceID by default), enrolled, deviceCredential
BiometricResultWhat queueBiometricResult() takes: 'success' or a BiometricsErrorCode
BiometricPromptOne of biometricPrompts(). reason is '' for a guarded read that gave none
FakeMicrophonePermissionWhat setMicrophonePermission() takes
FakeRecordedAudioWhat setRecordedAudio() takes: bytes, mimeType and durationMs
FakeAudioRecordingInfoWhat audioRecording() returns: state and maxDuration
FakeAudioFileWhat setAudioFile() takes: duration and error
FakeAudioPlaybackInfoWhat audioPlayback() returns: state, position, duration, track, remoteCommands