search
HomeWeb Front-endJS TutorialThe Missing Ingredient for Angular Template Code Coverage and Future-Proof Testing

TL;DR: Turn on Ahead-Of-Time (AOT) compilation for your Angular tests to get accurate template code coverage, faster test execution, production-symmetry, and future-proof tests.

The option is already available for Vitest users and will soon be available for Karma and Jest (experimental builder) users.

? 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 until recently, it was the only available option.

The problem is that JIT has a few significant downsides:

  • Code coverage is not accurate as the template is not taken into account.
  • It is slower as the tests compile the templates on the fly.
  • It is not future-proof as Angular has reached the limits of JIT compatibility. By design, some features are simply impossible to implement with JIT.
  • It is not symmetrical with the production environment, where AOT is used.

⏰ Why now?

Since Angular 8 and the introduction of IVy, 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. It has only been possible to enable AOT for testing since Vitest support for Angular was added by the Analog team.

As of November 2024:

  • Vitest is the only option that supports AOT compilation.
  • There are open PRs for Karma and Jest Experimental Builder to support AOT.

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 around 20% faster execution, 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. Using AOT, you will gain more confidence and achieve behavior that is closer to production.

? 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. Deferrable Views). Other potential features from the Angular roadmap, like selectorless components, will probably be impossible to use with JIT.

Actually, since Angular's Signal Inputs (and similar functional APIs), 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 prepared for whatever the future holds for JIT.

? 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></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 (⚠️ for now ️⚠️):

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

  return TestBed.createComponent(TestContainer);
}

My advice is to avoid such constructs as much as possible and prefer creating test-specific components when needed, 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:

  • It is less readable and more verbose.
  • "Mocking" (or providing test doubles) at the module level is less granular and can be less predictable.
  • It is highly coupled to the testing framework you are using.

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

  • For Angular CLI users, use Analog's schematic.
  • For Nx users, choose the vitest option when generating an application or library (available since Nx 20.1.0).

2. Enable AOT

Locate the vite.config.js file and turn on AOT by setting Angular's plugin jit option to false:

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

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

  return TestBed.createComponent(TestContainer);
}

? 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

Make sure you install the Vitest Istanbul version that matches Vitest's major version

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

  return TestBed.createComponent(TestContainer);
}

2. Choose istanbul as your coverage provider

Update the vite.config.mts to enable coverage using Istanbul:

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

? Watch it in Action

You can now run the tests:

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

then click on the coverage icon and admire the template's code coverage. ?

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

(you will also find the coverage report in the coverage folder)

Angular Template Coverage

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

It will even work for structural directives.

Angular Structural Directive Coverage

Now, guess what!?

The coverage also works for inline templates! ?

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.

Any observed statistical regularity will tend to collapse once pressure is placed upon it for control purposes.

-- Charles Goodhart

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

I'd add that the simplest metrics are often the most misleading.

? What's Next?

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

Jest users have three options:

  • Recommended: Migrate to Vitest. (? stay tuned as I'll soon be sharing the smoothest migration path)
  • Use the experimental builder with AOT.
  • Wait for jest-preset-angular AOT support.

Vitest users can enjoy the benefits of AOT right now. ?

? Additional Resources

  • ? Demo Repo
  • ? Angular Ahead-Of-Time (AOT) Compiler Docs
  • ? Vitest Docs
  • ? Analog's Docs on Vitest

??‍? Pragmatic Angular Testing Video Course is Here!

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

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

Learn practical, reliable testing strategies to keep your Angular apps stable and maintainable. (Now 50% off for a limited time!)

The above is the detailed content of The Missing Ingredient for Angular Template Code Coverage and Future-Proof Testing. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)