Marmicode
Blog Post
Younes Jaaidi

The Missing Ingredient for Angular Template Code Coverage and Future-Proof Testing

by Younes Jaaidi ā€¢ 
Nov 18, 2024 ā€¢ 6 minutes
The Missing Ingredient for Angular Template Code Coverage and Future-Proof Testing

// šŸ›‘ This is broken with AOT.
const fixture = render(`<app-button/>`, { imports: [Button] });

function render(template, { imports }) {
  @Component({
    template,
    imports,
  })
  class TestContainer {}

  return TestBed.createComponent(TestContainer);
}

function render(template, { imports }) {
  @Component({
    jit: true,
    template,
    imports,
  })
  class TestContainer {}

  return TestBed.createComponent(TestContainer);
}

// app.cmp.spec.ts
vi.mock('./street-map.cmp', async () => {
  return {
    StreetMap: await import('./street-map-fake.cmp').then(
      (m) => m.StreetMapFake
    ),
  };
});

// street-map-fake.cmp.ts
@Component({
  selector: 'app-street-map',
  template: 'Fake Street Map',
})
class StreetMapFake implements StreetMap {
  // ...
}

export default defineConfig({
  ...
  plugins: [
    angular({ jit: false }),
    ...
  ],
  ...
});

npm install -D @vitest/coverage-istanbul

export default defineConfig({
  ...
  test: {
    ...
    coverage: {
      provider: 'istanbul',
    },
  },
});

nx test my-app --coverage --ui --watch
# or
ng test --coverage --ui --watch