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.

referencesservices.md

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

Services

Contents

  1. Getting the Service
  2. Setup Functions
  3. Errors
  4. Signals
  5. Observables
  6. Effects, Resources and Signal Factories

Getting the Service

  • Always TestBed.inject(MealPlanner), never new MealPlanner(...): tests stay insensitive to how dependencies are injected, and to logic moving into other injectable services.

  • A root service needs no provider. Only provide fakes for the dependencies that must be replaced:

    TestBed.configureTestingModule({
      providers: [provideMealRepositoryFake()],
    });
  • Real collaborators (stores, orchestration services) stay real unless they make the test too complex — see principles.md.

  • If the service calls HttpClient directly and there is no repository to fake, see fakes.md.

Setup Functions

describe(MealPlanner, () => {
  it("adds recipes", async () => {
    const { mealPlanner, burger, salad } = createMealPlanner();

    await mealPlanner.addRecipe(burger);
    await mealPlanner.addRecipe(salad);

    expect(mealPlanner.recipes()).toEqual([
      expect.objectContaining({ name: "Burger" }),
      expect.objectContaining({ name: "Salad" }),
    ]);
  });

  it("does not allow recipe duplicates", async () => {
    const { mealPlanner, burgerDuplicate } =
      await createMealPlannerWithBurger();

    expect(mealPlanner.canAddRecipe(burgerDuplicate)).toBe(false);
  });

  /* Composed setup instead of options. */
  async function createMealPlannerWithBurger() {
    const { mealPlanner, burger, ...utils } = createMealPlanner();

    await mealPlanner.addRecipe(burger);

    return { mealPlanner, ...utils };
  }

  function createMealPlanner() {
    const { getMealPlanner, ...utils } = setUpMealPlanner();
    return { mealPlanner: getMealPlanner(), ...utils };
  }

  /* Deferred instantiation: lets tests arrange fakes before the constructor runs. */
  function setUpMealPlanner() {
    TestBed.configureTestingModule({
      providers: [provideMealRepositoryFake()],
    });

    return {
      getMealPlanner: () => TestBed.inject(MealPlanner),
      mealRepoFake: TestBed.inject(MealRepositoryFake),
      burger: recipeMother.withBasicInfo("Burger").build(),
      burgerDuplicate: recipeMother.withBasicInfo("Burger").build(),
      salad: recipeMother.withBasicInfo("Salad").build(),
    };
  }
});

Full example: examples/meal-planner/meal-planner.spec.ts.

Errors

/* Synchronous method: pass a function, not its result. */
expect(() => cart.add(burgerDuplicate)).toThrow(`Can't add item.`);

/* Method returning a promise. */
await expect(mealPlanner.addRecipe(burgerDuplicate)).rejects.toThrow(
  `Can't add recipe.`,
);

/* Method returning an observable. */
await expect(firstValueFrom(recipeRepo.search(filter))).rejects.toThrow(
  "Search failed.",
);

When the error type is part of the contract, assert it: toThrow(RecipeAlreadyAddedError).

Signals

Read signals directly:

expect(mealPlanner.recipes()).toMatchObject([{ name: "Burger" }]);

Reading a value after an action doesn't prove that it is reactive: a plain getter would pass too. When reactivity matters (the view depends on it), read the value through a computed, which only updates when its signal dependencies change:

it("notifies when recipes change", async () => {
  const { mealPlanner, salad } = await createMealPlannerWithBurger();

  const canAddSalad = watch(() => mealPlanner.canAddRecipe(salad));

  await mealPlanner.addRecipe(salad);

  expect(canAddSalad()).toBe(false);
});

If the project has no such helper, add it to the shared testing utilities:

import { computed, Signal } from "@angular/core";

/**
 * Returns a signal that only updates if `fn` is reactive.
 */
export function watch<T>(fn: () => T): Signal<T> {
  const computedSignal = computed(fn);
  /* Read once to populate the computed signal's cache. */
  computedSignal();
  return computedSignal;
}

Observables

  • One value: convert to a promise.

    const meals = await lastValueFrom(mealRepo.getMeals()); // completes
    const recipes = await firstValueFrom(mealPlanner.recipes$); // never completes
  • Several values over time: subscribe with a spy, unsubscribe when the test finishes, and clear the initial emission when another test covers it.

    it("emits recipes when added", async () => {
      const { mealPlanner, burger } = createMealPlanner();
    
      const next = vi.fn<(recipes: Recipe[]) => void>();
      const subscription = mealPlanner.recipes$.subscribe(next);
      onTestFinished(() => subscription.unsubscribe());
    
      next.mockClear();
    
      await mealPlanner.addRecipe(burger);
    
      expect(next).toHaveBeenCalledExactlyOnceWith([
        expect.objectContaining({ name: "Burger" }),
      ]);
    });
  • Test the initial emission in its own test (e.g. emits an empty array initially): forgetting it is a common bug with observables.

  • Test errors too. For a single value: await expect(firstValueFrom(source$)).rejects.toThrow('...'). Over time: subscribe with { next, error } spies and assert on error.

  • Never use the done callback: it fails late with a timeout, stops at the first value, and invites nested callbacks.

Effects, Resources and Signal Factories

  • Prefer testing effects and resources through the service or component that uses them, and assert the outcome with await expect.poll(() => ...).

  • Don't reach for TestBed.tick() (or the deprecated TestBed.flushEffects()) to make a test pass: Angular's synchronization is an implementation detail.

  • To test a signal factory that needs an injection context on its own, wrap it with a helper:

    it("auto-saves the recipe when it changes", async () => {
      TestBed.configureTestingModule({ providers: [provideStorageFake()] });
      const storage = TestBed.inject(StorageFake);
      const recipe = signal("babaganoush");
    
      await runInAngular(() => {
        autoSave("favorite-recipe", recipe);
        recipe.set("burger");
      });
    
      expect(storage.getSync("favorite-recipe")).toBe('"burger"');
    });
    
    async function runInAngular<RETURN>(
      fn: () => RETURN | Promise<RETURN>,
    ): Promise<RETURN> {
      return TestBed.runInInjectionContext(async () => {
        const appRef = inject(ApplicationRef);
        const result = await fn();
        await appRef.whenStable();
        return result;
      });
    }

    Think twice before narrowing down tests to that granularity.

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