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.

referencescomponents.md

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

Components

Contents

  1. Choosing the Test Flavor
  2. Mounting Without the Fixture
  3. Inputs, Outputs and Models
  4. Locating Elements
  5. Interacting
  6. Asserting
  7. Shallow Tests
  8. Host Components
  9. Pipes and Directives
  10. Angular Material and CDK

Choosing the Test Flavor

Flavor What it does When
Integration Renders the component with its real children ✅ Default. Presentational components, and containers that stay simple enough
Shallow Renders the component without its children, checks what it passes to their inputs and how it reacts to their outputs ⚠️ Last resort, to narrow down: children are slow, complex, widely shared, not implemented yet, or make failures hard to diagnose
Renderless ("isolated") Injects the component class like a service and calls its methods ❌ Avoid
  • Integration tests are the most meaningful (closest to the user) but the slowest, and changes in shared children can break many of them.
  • Shallow tests are fast and precise, and insensitive to the children's internals. They are coupled to the parent ↔ children interface (inputs and outputs), so choose that boundary wisely.
  • Renderless tests are coupled to implementation details (they break when switching from subscribe to the async pipe to signals), can exercise impossible states (calling search() while the form is disabled), and miss template bugs. If a component's logic is complex enough to tempt you, move it to a service and test the service.

Mounting Without the Fixture

function mountRecipeSearch() {
  /* 1. Providers: fakes for adapters only. */
  TestBed.configureTestingModule({
    providers: [provideRecipeRepositoryFake()],
  });

  /* 2. Arrange the fakes. */
  TestBed.inject(RecipeRepositoryFake).setRecipes([
    recipeMother.withBasicInfo("Burger").build(),
    recipeMother.withBasicInfo("Salad").build(),
  ]);

  /* 3. Mount. The returned fixture is deliberately ignored. */
  TestBed.createComponent(RecipeSearch);

  /* 4. Return locators and gloves. */
  return {
    recipeNames: page.getByRole("heading"),
  };
}
  • Order: install fake timers if needed → configure providers → arrange fakes → TestBed.createComponent(...).
  • bindings requires Angular ≥ 20.1. On older versions, keep the fixture and set inputs with fixture.componentRef.setInput().
  • The view renders asynchronously. Locator actions and expect.element wait for it: don't add detectChanges(), whenStable() or sleeps.
  • Add the providers the app normally registers at bootstrap only if the component needs them (e.g. provideRouter([]) for routerLink).
  • Errors thrown while rendering or in event listeners fail the test. Never disable rethrowApplicationErrors.
  • Non-standalone components go in declarations, with their NgModule dependencies in imports, in TestBed.configureTestingModule. Everything else (no fixture, bindings, locators, overrideComponent for shallow tests) is identical. Don't migrate the component to standalone just to test it.
  • @defer blocks play through like in the browser (DeferBlockBehavior.Playthrough is TestBed's default): test the deferred content through the DOM. The only reason to touch the fixture is when the @placeholder / @loading states are themselves the behavior under test (deferBlockBehavior: DeferBlockBehavior.Manual + fixture.getDeferBlocks()).

Inputs, Outputs and Models

Inputs — bind a signal, then set it to change the input:

function mountRecipePreview() {
  const recipe = signal(recipeMother.withBasicInfo("Burger").build());

  TestBed.createComponent(RecipePreview, {
    bindings: [inputBinding("recipe", recipe)],
  });

  return { recipe, recipeName: page.getByRole("heading") };
}

it("shows the new recipe when the input changes", async () => {
  const { recipe, recipeName } = mountRecipePreview();

  recipe.set(recipeMother.withBasicInfo("Salad").build());

  await expect.element(recipeName).toHaveTextContent("Salad");
});
  • Bind every required input at creation: reading an unset input.required() throws.
  • For a value that never changes, a function is enough: inputBinding('recipe', () => burger).
  • On Angular < 20.1, inputBinding doesn't exist: keep the fixture and call fixture.componentRef.setInput('recipe', burger).

Outputs — listen with a spy:

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

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

await page.getByLabelText("Max Ingredients").fill("3");

expect(filterChangeSpy).toHaveBeenLastCalledWith(
  expect.objectContaining({
    maxIngredientCount: 3,
  } satisfies Partial<RecipeFilterCriteria>),
);

If the output is delayed (e.g. debounced), control time first: see time.md.

Models — model() creates an input and a <name>Change output. Either spy on the output as above, or bind both directions to a writable signal:

const filter = signal(createDefaultRecipeFilterCriteria());

TestBed.createComponent(RecipeFilter, {
  bindings: [twoWayBinding("filter", filter)],
});

await page.getByLabelText("Keywords").fill("Burger");

await expect.poll(() => filter()).toMatchObject({ keywords: "Burger" });

Inputs, outputs and models are imported from @angular/core (inputBinding, outputBinding, twoWayBinding).

Locating Elements

Use the page API from vitest/browser, in this order of preference: getByRole, getByLabelText, getByPlaceholder, getByText, getByAltText / getByTitle, and getByTestId as a last resort.

  • When several elements match, scope to the container the user would look at instead of picking by position:

    page
      .getByRole("article")
      .filter({ hasText: "Burger" })
      .getByRole("button", { name: "ADD" });
  • Don't locate elements with CSS classes or component selectors.

  • Not finding an element by role or label usually reveals an accessibility issue. Point it out, or fix the markup if the task allows it (a <label>, an aria-label, a semantic element such as <article>), instead of falling back to CSS.

Interacting

  • Act like a user, through locator actions: click(), fill(), clear(), selectOptions(), hover(). They go through the browser provider with actionability checks, so a test can't click a button that users can't reach.
  • Don't call component methods, set component properties, dispatch events manually, or use Testing Library's userEvent in Browser Mode.
  • For what users don't do through this component (e.g. data changed elsewhere in the app), act through the real service or the fake: await mealPlanner.addRecipe(burger).

Asserting

  • What the user sees: await expect.element(locator).toHaveTextContent(...), .toBeDisabled(), .toBeVisible(), .toHaveLength(n).
  • Side effects on application state: await expect.poll(() => getMealPlannerRecipeNames()).toEqual(['Burger']). Don't render another page (e.g. the meal plan) to verify a side effect: the test would become too wide.
  • Outputs: assert on the spy after the action.

Shallow Tests

function mountRecipeSearch() {
  TestBed.configureTestingModule({
    providers: [provideRecipeRepositoryFake()],
  });

  /* Must happen before `createComponent`. */
  TestBed.overrideComponent(RecipeSearch, {
    set: {
      /* Whitelist what the template needs (e.g. pipes), drop child components. */
      imports: [],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    },
  });

  TestBed.inject(RecipeRepositoryFake).setRecipes([
    recipeMother.withBasicInfo("Burger").build(),
    recipeMother.withBasicInfo("Salad").build(),
  ]);

  TestBed.createComponent(RecipeSearch);

  return {
    /* Read what the parent passes to the children's inputs. */
    getRecipePreviewNames: () =>
      page
        .getByTestId("recipe-preview")
        .elements()
        .map((el) => new DebugElement(el).properties["recipe"].name),
    /* Simulate a child's output. */
    updateFilter: async (filter: RecipeFilterCriteria) => {
      const filterEl = await vi.waitFor(() =>
        page.getByTestId("recipe-filter").element(),
      );
      new DebugElement(filterEl).triggerEventHandler("filterChange", filter);
    },
  };
}

it("searches recipes using the filter emitted by recipe filter", async () => {
  const { getRecipePreviewNames, updateFilter } = mountRecipeSearch();

  await updateFilter({
    keywords: "Burg",
    maxIngredientCount: null,
    maxStepCount: null,
  });

  await expect.poll(() => getRecipePreviewNames()).toEqual(["Burger"]);
});
  • Locate child placeholders through a data-testid on the child's host element in the parent's template (e.g. <wm-recipe-preview data-testid="recipe-preview" [recipe]="recipe">): inert custom elements have no role or label.
  • Whitelist imports with set rather than removing children one by one: it's cheaper to maintain and keeps tests fast.
  • CUSTOM_ELEMENTS_SCHEMA turns unknown children into inert custom elements; their bindings become element properties (signal inputs included). If Angular still complains about unknown properties on directives, use NO_ERRORS_SCHEMA.
  • A shallow SUT may include more than one component: keep the children that belong to the same unit of behavior.

Full example: examples/shallow/recipe-search.browser.spec.ts. In a project, put the spec next to the component.

Host Components

For content projection, directives, or anything that needs a parent template, declare a small host component in the spec:

@Component({
  imports: [RecipePreview],
  template: `<wm-recipe-preview [recipe]="burger">
    <button>Cook</button>
  </wm-recipe-preview>`,
})
class RecipePreviewHost {
  burger = recipeMother.withBasicInfo("Burger").build();
}

it("projects content", async () => {
  TestBed.createComponent(RecipePreviewHost);

  await expect
    .element(page.getByRole("article").getByRole("button", { name: "Cook" }))
    .toBeVisible();
});

Pipes and Directives

  • Pipes: inject the pipe class with TestBed.inject(MyPipe) (provide it in TestBed.configureTestingModule unless @Pipe sets providedIn: 'root'. @Pipe is unchanged by @Service) and test transform() as a pure function. Render it in a host component only when the behavior depends on the template (e.g. a pipe that subscribes, like async).
  • Directives: always through a host component and the DOM, never by instantiating the directive class.

Angular Material and CDK

  • Use them for real and locate their elements by role or label: mat-label is associated with its input, so page.getByLabelText('Keywords') works.
  • Overlays (dialogs, menus, snack bars) render outside the component's host element. page locators search the whole page, so they find them: await expect.element(page.getByRole('dialog')).toMatchTextContent('Delete this recipe?') (toHaveTextContent on Vitest 4).
  • If they make a test slow or complex, wrap them in your own abstraction and fake it: see fakes.md.

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