Marmicode
Blog Post
Younes Jaaidi

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

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

šŸ˜§ What's wrong with JIT?

Whether you are using Karma, Jest, or Vitest, you are probably using Just-In-Time (JIT) compilation for your Angular tests, as .

The problem is that JIT has a few significant downsides:

ā° Why now?

Since Angular 8 and the introduction of , the Angular compiler has started transforming templates into instructions. Among many other benefits, this also meant that code coverage tools could map these instructions to the template and compute the code coverage accordingly.

Theoretically, it has been possible to produce code coverage by running tests with AOT since Angular 8, but the option was not available in Karma or Jest. .

As of November 2024:

Angular Template Coverage

šŸŽ Other Benefits of AOT Testing

āš”ļø Faster Test Execution

Whether you are using JIT or AOT, components will end up being compiled at some point. The main difference is that with AOT, the compilation is done once and can be cached, while with JIT, each test module might end up recompiling components.

This means that even if the transform phase is a bit slower with AOT, the overall test execution time will be faster. The numbers I've seen indicate , but this will depend heavily on the structure of your tests and the System Under Test.

šŸ‘Æ Production-Symmetry

We generally want our tests to be as symmetric as possible to the production environment to increase confidence. This is often challenging as it balances against other properties like the speed of the tests, the size of the System Under Test, or predictability.

The interesting aspect of AOT is that it improves production-symmetry without harming other properties.

šŸ”® Future-Proof Tests

More importantly, JIT has reached its limits and is becoming a liability for Angular. For instance, some Angular features are simply not supported in JIT (e.g. ). Other potential features from the Angular roadmap, like selectorless components, will be impossible to use with JIT.

Actually, since Angular's Signal Inputs , JIT already requires some minimal transforms to work.

By switching to AOT, you are making your tests future-proof, ready to benefit from any innovation, and

šŸ¤” Drawbacks

šŸŖ„ Dynamic Component Constructs Should Be Avoided

By turning on AOT, some techniques that rely on dynamic constructs will break.

For instance, such usage will not work anymore:

// šŸ›‘ 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);
}

However, bypassing the AOT compilation is still possible :

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

  return TestBed.createComponent(TestContainer);
}

My advice is to , even though it might be a bit more verbose. In the future, the Angular team could provide alternatives that are both AOT-compatible and less boilerplat-y.

šŸ¦¦ Shallow Testing is More Challenging

While Shallow Testing should not be your primary testing strategy as it is also less production-symmetric, it is still a useful technique to have in your toolbox.

With AOT, it is currently impossible to override a component's imports using TestBed#overrideComponent.

The workaround is to override the component's dependencies at the module level using the testing framework's API and replace components with their test doubles.

For example, with Vitest:

// 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 {
  // ...
}

While this temporary workaround is AOT-compatible, it comes with a cost:

For now, I would recommend using JIT for Shallow Tests until TestBed#overrideComponent supports AOT or until the Angular team provides a better alternative. You can achieve this by using a separate configuration for Shallow Tests that use JIT for tests matching a specific pattern like *.jit.spec.ts.

šŸ‘ØšŸ»ā€šŸ³ Taking Vitest with AOT for a Spin

1. Set up Vitest

2. Enable AOT

Locate the vite.config.js file and :

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

šŸ“ˆ Configure Code Coverage

We have the option to use either istanbul or native v8 for code coverage. For some reason, still under investigation, Vitest coverage remapping fails when using v8. The solution is to fall back to using istanbul instead.

1. Install @vitest/coverage-istanbul

npm install -D @vitest/coverage-istanbul

2. Choose istanbul as your coverage provider

Update the vite.config.mts to using Istanbul:

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

šŸŽ¬ Watch it in Action

You can now run the tests:

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

then click on the coverage icon and admire the template's code coverage. šŸ¤Æ

vitest-coverage-button

Angular Template Coverage

Note that the coverage is computed based on the instructions generated by the compiler, which means that:

Angular Structural Directive Coverage

Now, guess what!?

Angular Inline Template Coverage

ā˜¢ļø Mind the Code Coverage Trap

While code coverage is a useful tool, it should be used wisely. Keep it as an indicator, not a rigid goal.

In other words, when a measure becomes a target, it ceases to be a good measure.

I'd add that .

šŸš€ What's Next?

Karma users will soon be able to enable AOT with a simple flag.

Jest users have three options:

Vitest users can enjoy the benefits of AOT right now. šŸŽ‰

šŸ“š Additional Resources

šŸ‘ØšŸ»ā€šŸ« Pragmatic Angular Testing Video Course is Here!

If you are tired of bugs, or high-maintenance tests that break at each refactor, my video course, , is here to help!

Learn practical, reliable testing strategies to keep your Angular apps stable and maintainable.


šŸ’¬