Testing utilities
Create type-safe partial mocks with fromPartial
The @octopus-energy/vitest/utils entrypoint currently exports one utility: fromPartial.
It lets you supply just the fields a test needs when the surrounding API expects a complete type.
See the API reference for the function's type signature.
fromPartial is a runtime no-op: it returns the same object and does not fill in missing fields
or validate data. Include every field the code under test reads.
Infer the type from context
Use fromPartial where TypeScript already knows the expected type:
import { fromPartial } from "@octopus-energy/vitest/utils";
interface User {
id: string;
profile: {
name: string;
email: string;
};
}
const user: User = fromPartial({ profile: { name: "Ada" } });The input is deeply partial, so nested fields can be omitted too. Fields you do provide are still checked against the expected type.
Configure mocked functions
A mocked function's return type supplies the context, avoiding manual casts:
import { fromPartial } from "@octopus-energy/vitest/utils";
import { expect, test, vi } from "vitest";
import { getUser } from "./users.ts";
vi.mock("./users.ts");
test("loads a user's name", async () => {
vi.mocked(getUser).mockResolvedValue(fromPartial({ name: "Ada" }));
const user = await getUser();
expect(user.name).toBe("Ada");
});This example assumes getUser returns a promise of a user object with a name field.
For synchronous functions, use mockReturnValue instead of mockResolvedValue.
Use an explicit type when there is no context
If you create a standalone mock value, supply the type argument:
const user = fromPartial<User>({ profile: { name: "Ada" } });Without contextual typing or an explicit type argument, the result is unknown.