Index of every page on this site: llms.txt
All skills
marmicode avatar

/angular-testing

@fa09f8d
by marmicodemarmicode/skills17 stars
Run it yourself

Writes, fixes and reviews Angular tests following the Pragmatic Angular Testing approach — fakes over mocks, real collaborators by default, components tested through the DOM rather than through fixtures. Targets Vitest (Browser Mode preferred, jsdom and happy-dom supported) and also applies to Jest, Jasmine/Karma and Angular Testing Library projects, including migrating them to Vitest. Use whenever adding, editing, reviewing or debugging unit tests in an Angular project — *.spec.ts files, TestBed, components, services (`@Service` or `@Injectable`), signals, guards, routing, and timers — including when tests are written as part of a feature or bug fix, when replacing mocks or spies with fakes, when declaring or faking a service, and when fixing slow or flaky tests. Prefer this over general Angular skills for anything test-related. Not for Playwright or Cypress end-to-end tests.

Use this Skill: https://skilld.dev/gh/marmicode/skills/angular-testing

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencestime.md

≈1.6k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Time

Debounce, throttling, delays, polling, auto-dismissed toasts, dates.

Contents

  1. Decide First
  2. Testing the Timing Itself: Manual Mode
  3. Skipping Delays: Fast-Forward Mode
  4. Dynamic Timing Configuration
  5. Rules

Decide First

  1. Must the other timers keep running for real? (e.g. fake timers break something else in the exercised code) → Dynamic timing configuration.
  2. Is the timing the behavior under test? ("no search before 300ms", "toast disappears after 5s") → fake timers in manual mode.
  3. Otherwise the timing is just in the way → fake timers in fast-forward mode, so that changing a debounce doesn't break or slow down unrelated tests.

Testing the Timing Itself: Manual Mode

In manual mode (Vitest's default), time stands still until the test advances it. That also pauses Angular's own scheduling: flush it right after mounting.

describe(RecipeFilter, () => {
  it("does not trigger filterChange output before debounce", async () => {
    const { filterChangeSpy, setInputValue } = await mountRecipeFilter();

    await setInputValue("Keywords", "Cauliflower");

    /* Debounce is 300ms: stay ~10ms away from the boundary. */
    await vi.advanceTimersByTimeAsync(290);

    expect(filterChangeSpy).not.toHaveBeenCalled();
  });

  it("triggers filterChange output after debounce", async () => {
    const { filterChangeSpy, setInputValue } = await mountRecipeFilter();

    await setInputValue("Keywords", "Cauliflower");

    await vi.advanceTimersByTimeAsync(310);

    expect(filterChangeSpy).toHaveBeenLastCalledWith(
      expect.objectContaining({
        keywords: "Cauliflower",
      } satisfies Partial<RecipeFilterCriteria>),
    );
  });

  async function mountRecipeFilter() {
    /* Install fake timers before creating the component... */
    vi.useFakeTimers();
    onTestFinished(() => {
      vi.useRealTimers();
    });

    const filterChangeSpy = vi.fn<(filter: RecipeFilterCriteria) => void>();

    TestBed.createComponent(RecipeFilter, {
      bindings: [
        outputBinding<RecipeFilterCriteria>("filterChange", filterChangeSpy),
      ],
    });

    /* ...then flush Angular's pending synchronization (paused by fake timers). */
    await vi.runAllTimersAsync();

    return {
      filterChangeSpy,
      setInputValue: (
        label: "Keywords" | "Max Ingredients" | "Max Steps",
        value: string,
      ) => page.getByLabelText(label).fill(value),
    };
  }
});

Without that flush, Angular can't render: locator actions time out and fixture.whenStable() never resolves.

If the component starts its own timers when it's created (an interval, an auto-dismissed toast), vi.runAllTimersAsync() would run them too, and it gives up after 10,000 timers with intervals. Flush with a bounded await vi.advanceTimersByTimeAsync(0) instead, then advance time explicitly.

Skipping Delays: Fast-Forward Mode

In fast-forward mode, the fake clock advances on its own as soon as a timer is scheduled. Delays are skipped without the test knowing their durations. It requires Vitest ≥ 4.1 and works with expect.element and expect.poll.

it('filters recipes by keywords', async () => {
  const { recipeNames, updateFilter } = mountRecipeSearch();

  await updateFilter({ keywords: 'Burg' }); // debounced, but no waiting

  await expect.element(recipeNames).toHaveTextContent('Burger');
});

function mountRecipeSearch() {
  vi.useFakeTimers();
  vi.setTimerTickMode('nextTimerAsync');
  onTestFinished(() => {
    vi.useRealTimers();
  });

  TestBed.configureTestingModule({ ... });

  TestBed.createComponent(RecipeSearch);

  return { ... };
}

Fast-forward mode is not synchronous: it advances time in a macrotask, so it applies once the test awaits something.

Dynamic Timing Configuration

Make durations injectable, and let tests make them instant or endless. No timer is intercepted, so Angular's scheduling runs normally, and tests don't depend on the testing framework.

/* Angular ≥ 22.1. Before that: @Injectable({ providedIn: 'root' }). */
@Service()
export class FormsTimingConfig {
  inputDebounce = 300;
}

export function provideFormsTimingConfig(
  config: FormsTimingConfig,
): Provider[] {
  return [{ provide: FormsTimingConfig, useValue: config }];
}

const MAX_TIMEOUT = Math.pow(2, 31) - 1;

export function provideTestingFormsTimingConfig(
  mode: "instant-debounce" | "never-ending-debounce",
) {
  return provideFormsTimingConfig({
    inputDebounce: mode === "instant-debounce" ? 0 : MAX_TIMEOUT,
  });
}
it("disables submit button while waiting for debounce", async () => {
  TestBed.configureTestingModule({
    providers: [provideTestingFormsTimingConfig("never-ending-debounce")],
  });

  // ... mount the component and fill the form ...

  await expect
    .element(page.getByRole("button", { name: "Submit" }))
    .toBeDisabled();
});

Trade-off: with different durations than production, things can run in a different order (e.g. an auto-save and a debounce). Angular Material's MATERIAL_ANIMATIONS token is a real-life example of this approach.

Rules

  • Install fake timers before creating components or services, never in the middle of a test.
  • Always restore real timers with onTestFinished(() => vi.useRealTimers()).
  • Only use the *Async APIs: advanceTimersByTimeAsync, runAllTimersAsync, runOnlyPendingTimersAsync. The synchronous ones skip microtasks and produce impossible behavior.
  • Approximate time (delay - 10, delay + 10): nested timers add extra milliseconds.
  • Stick to one mode per test.
  • When an error is expected after a delay, set up await expect(promise).rejects.toThrow(...) before advancing time, or use fast-forward mode: in manual mode, a promise that rejects during vi.advanceTimersByTimeAsync(...) becomes an unhandled rejection before the assertion can catch it.
  • Never use fakeAsync, tick(), flush() or waitForAsync: they depend on Zone.js. Vitest fake timers work with and without zones.
  • Control the current date with vi.setSystemTime(...). Without fake timers, it only mocks Date and doesn't pause Angular. Restore it with onTestFinished(() => vi.useRealTimers()).

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts11d3 checks · Risk SAFE
  • Gen Agent Trust Hub11d

    The skill provides comprehensive guidelines and examples for writing Angular tests using Vitest and other industry-standard tools. It promotes testing best practices like using fakes and browser-mode integration testing. No malicious patterns, obfuscation, or security risks were identified.

  • Socket11d

    No alerts

  • Snyk11d

    Risk: LOW · No issues

Signed by skilld at fa09f8d. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 weeks ago.

Activeupdated 2 weeks ago

README badge

README badge for marmicode/skills/angular-testing