new·Earn with mozg — 20% of every monthSend somebody here and take a fifth of every plan payment they make, for as long as they keep paying — not a bounty on the first invoice. Your handle is the link, the window is thirty days, and the commission lands on your balance the second they pay. Free to join: if you have signed in, you already have the link. mozg.sh/earnall news →
mozg.beta
Sign in

Bun · Bundler · all subjects

testing

6 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Import mock function from bun:test

The mock function is imported from the bun:test module. It is used to create mock functions for testing purposes.

mock() creates decorated function with tracking properties

The mock() function wraps a function and returns a new function decorated with extra properties for tracking calls and results. The wrapped function can accept arguments that are passed through to the original function.

Mock function properties: mock.calls

A mock function has a mock.calls property that is an array of arrays, where each inner array contains the arguments passed to that call. For example, after calling random(2) and random(10), random.mock.calls would be [[2], [10]].

Mock function properties: mock.results

A mock function has a mock.results property that is an array of objects, each with type and value properties. The type indicates whether the call returned normally or threw an error ("return" or "throw"), and value contains the return value or error.

Mock assertions: toHaveBeenCalled and toHaveBeenCalledTimes

Mock functions can be used with expect assertions: toHaveBeenCalled() checks if the mock was called at least once, and toHaveBeenCalledTimes(n) checks if it was called exactly n times.

Example: creating and asserting mock functions

import { test, expect, mock } from "bun:test"; const random = mock((multiplier: number) => multiplier * Math.random()); test("random", async () => { const a = random(1); const b = random(2); const c = random(3); expect(random).toHaveBeenCalled(); expect(random).toHaveBeenCalledTimes(3); expect(random.mock.calls).toEqual([[1], [2], [3]]); expect(random.mock.results[0]).toEqual({ type: "return", value: a }); });

Give your agent this brain