---
name: unit-tests
description: >-
  Authors Jest unit tests for TypeScript services using testdouble, neverthrow ResultAsync, and a structured mocks class. Use when writing or refactoring unit tests, adding test coverage, or when the user asks for tests matching project conventions (Arrange/Act/Assert, explicit mocks, negative-only td.verify).
license: MIT
metadata:
  author: 1Shot-API
  version: "1.0.0"
  repository: https://github.com/1Shot-API/skills
title: unit-tests
canonical_url: https://skilld.dev/gh/1shot-api/skills/unit-tests
last_updated: 2026-11-12T09:13:01.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install 1shot-api/skills/unit-tests`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/unit-tests`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/1shot-api/skills/unit-tests) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/unit-tests`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/unit-tests --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/unit-tests --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Unit tests (service / business layer)

Follow this structure so tests stay readable, explicit, and easy to maintain. Reference implementations (in the oneshot monorepo):

- `packages/signer/test/unit/business/SignerService.test.ts` — parameterized mocks class, explicit Redis key matching, `getInstance()`.
- `packages/EVMBaseChain/test/unit/business/EscrowWalletService.test.ts` — shared `CommonValues`, heavy domain setup in Arrange, `factoryService()`.

## Install this skill (consumer / global)

```bash
npx skills add 1Shot-API/skills/unit-tests -g -a claude-code -y
```

## When to use this skill

- Writing or refactoring Jest unit tests for TypeScript services in the oneshot monorepo
- Adding coverage that should match project conventions (testdouble, neverthrow `ResultAsync`)
- The user asks for tests matching Arrange/Act/Assert, explicit mocks, or negative-only `td.verify`

## When NOT to use this skill

- Frontend/portal component tests that do not use the service mocks class pattern
- Integration or e2e tests outside the Jest + testdouble service layer style
- Relayer (`1shot-okx-relayer`) tests that use `bun:test` instead of Jest/testdouble

## 1. File-level constants

At the top of the test file (after imports), declare **named constants** used across tests:

- **Stable IDs and branded types** (`UserId`, `BusinessId`, addresses) so every test uses the same fake identity unless a case needs a different value.
- **Shared primitives** reused in mocks (e.g. JWT strings, chain enum) when they are not test-specific.

Use real or fake values deliberately: prefer values that match production shape (UUIDs, `0x`-prefixed addresses) so type constructors and validators behave like production.

## 2. `ClassUnderTestMocks` class

Create one class named after the system under test, e.g. `SignerServiceMocks`, `EscrowWalletServiceMocks`.

- **Constructor parameters**: Pass anything that should vary the **baseline** behavior across tests (e.g. `userId`, `EService` for the chain service token). Tests that need the same baseline use the same arguments; divergent tests pass different constructor args **or** override in Arrange (see below).

## 3. Dependencies

The mocks class **owns every dependency** the class-under-test needs:

- `td.object<Interface>()` for each injected port (repository, config provider, Redis, etc.).
- Public fields so tests and overrides can reference them (`mocks.kmsRepository`, `mocks.redisClient`, …).

Wire the real constructor in a single factory method:

- Name it `getInstance()`, `factoryService()`, or another clear name; one place constructs `new ClassUnderTest(...)`.

## 4. Baseline = happy path in the constructor

In the **constructor** (or an `init()` called from it), set **`td.when(...).thenReturn(...)`** for the default, success-path behavior:

- `getConfig()` → `okAsync` a real-enough config object.
- `getRedisClient()` → `okAsync` the mock Redis client.
- Any stubbed remote call that most tests expect to succeed.

**Prefer explicit arguments** in `td.when()`:

- Pass concrete `CreateSigningKeyParams`-like values, exact `RedisKeys.*` arrays, or `td.matchers.contains([...])` with real key strings when the implementation builds a known list.
- Avoid `td.matchers.anything()` in baseline stubs unless the API is truly opaque; the tighter the match, the earlier wrong calls fail.

Complex or repeated payloads (resolved user context, config blobs) can be built in **protected helpers** or **factory methods** on the mocks class.

## 5. Public members and factories

Expose on the mocks class:

- **Data the SUT needs from outside**: e.g. `ruc`, `config`, prebuilt `SignerConfig`.
- **Factory methods** for verbose objects (`makeRucForUserAndChainService`, etc.) when multiple tests need the same shape with small variations.

## 6. Test structure: Arrange / Act / Assert

Each `test(...)` (or `it(...)`) uses three sections with **comments**:

```ts
test("descriptive name", async () => {
	// Arrange
	const mocks = new SomeServiceMocks(/* baseline params */);
	// Optional: td.when overrides for this test only
	const svc = mocks.getInstance();

	// Act
	const result = await svc.someMethod(...);

	// Assert
	expect(result.isErr()).toBe(true);
	// ...
});
```

## 7. Arrange

- Instantiate **`ClassUnderTestMocks`** with the right constructor args.
- Apply **overrides** after construction: extra `td.when(mocks.dep.method(explicitArgs)).thenReturn(...)` for this test only (e.g. kill switch returns `["on"]`).
- End Arrange with **`const sut = mocks.getInstance()`** (or `factoryService()`).

## 8. Act

- **Only** calls on the system under test (and sometimes one obvious preparatory call if the scenario requires it). No assertions in Act.

## 9. Assert

- **Primary**: `expect(...)` on the method result — for `ResultAsync` / neverthrow, `result.isOk()`, `result.isErr()`, `_unsafeUnwrap()`, `_unsafeUnwrapErr()`, `toBeInstanceOf`, deep equality on unwrapped values.
- **Avoid** `td.verify` for happy-path call counts unless the team explicitly wants interaction testing for that case.

## 10. `td.verify` — negative guarantees only

Use **`td.verify(..., { times: 0 })`** when the test’s purpose is to prove something **did not run** (e.g. KMS not called after validation failure, or Redis kill switch short-circuits before repository access).

When `verify` is required, still prefer **specific arguments** where feasible; use `anything()` only for parameters that are intentionally opaque or unstable.

## Naming consistency

- Mocks class: `{ClassUnderTest}Mocks` (e.g. `SignerServiceMocks`).
- Factory: `getInstance()` or `factoryService()` — pick one per file and stay consistent.
- Fix typos in dependency field names (`repository` not `repsitory`) in new tests.

## Checklist for a new test file

- [ ] Constants block for shared IDs / tokens / addresses
- [ ] Single mocks class with all `td.object` dependencies
- [ ] Constructor establishes happy-path `td.when` with explicit values where possible
- [ ] `getInstance` / `factoryService` builds the real service
- [ ] Each test has `// Arrange`, `// Act`, `// Assert`
- [ ] Assert focuses on `expect` on results; `td.verify` only for must-not-happen side effects
