GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Allow using `vi.mock` (and related) functions in tests · Issue #32641 · angular/angular-cli

Allow using vi.mock (and related) functions in tests #32641

New issue
Copy link
New issue
Copy link
Open
Open
Allow using vi.mock (and related) functions in tests#32641
Copy link
Labels
angular/build:unit-testarea: @angular/build
Milestone
needsTriage

Description

@MillerSvt
MillerSvt
opened on Mar 2, 2026
Issue body actions

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

With the new Angular unit-test builder (Vite), test files are bundled into unified chunks.
Because of this full bundling step:

  • ESM modules are statically linked at build time
  • There is no runtime module graph available
  • vi.mock() cannot intercept module loading
  • Mocking entire modules (components/services/modules) is not possible

Currently if we use vi.mock function for automocking component/directives/services/pipes/etc..., we got an error:

Error: The "vi.mock" and related methods are not supported with the Angular unit-test system. Please use Angular TestBed for mocking.

TestBed overrides are insufficient because:

  • They replace Angular metadata (providers/imports), not module implementation
  • They cannot replace pure TS logic or side effects
  • They do not intercept ESM import bindings

Proposed solution

Instead of runtime interception (like Vitest normally does), Angular test builder should:

  1. Detect vi.mock() calls at compile time (in spec files, and in setupFiles)
  2. Hoist them
  3. Rewrite import bindings to use a generated mock registry
  4. Replace module resolution during bundling

I suggest to create esbuild plugin, that:

  1. Parse test file AST
  2. Detect:
  • vi.mock()
  • vi.unmock()
  • vi.doMock()
  • vi.doUnmock()
  • vi.importMock()
  • vi.importActual()
  • vi.hoisted()
  1. Hoist mock calls
  2. Rewrite imports

Example Transform Injectable

Before:

import { MyService } from './my-service';
import { MyOtherService } from './my-other-service';

vi.mock('./my-service', () => ({
  MyService:
    @Injectable({providedIn: 'root'})
    class {
      get() { return 'mock'; }
    }
}));

vi.mock('./my-other-service');

test(() => {
  const myService = new MyService();
  const myOtherService = new MyOtherService();
});

After:

// should initialize once in one environment
const __angularViMocks = (globalThis.__angular_vi_mocks ??= new Map<string, any>());

__angularViMocks.set(
  './my-service',
  (() => ({
    MyService: class {
      get() { return 'mock'; }
      static ɵprov = {
         providedIn: 'root',
         factory: () => new this();
      };
      static ɵfac = () => new this(); 
    }
  }))()
);

__angularViMocks.set(
  './my-other-service',
  (() => ({
    MyOtherService: class {
      get = vi.fn(); // maybe better to put `vi.fn()` to MyOtherService.prototype.get = vi.fn();
      static ɵprov = {
         providedIn: 'root',
         factory: () => new this();
      };
      static ɵfac = () => new this(); 
    }
  }))()
);

import * as __angularViActualMod1 from './my-service';
import * as __angularViActualMod2 from './my-other-service';

// We should replace that import in every dependent chunk.
const { MyService } = __angularViMocks.get('./my-service') ?? __angularViActualMod1;
const { MyOtherService } = __angularViMocks.get('./my-other-service') ?? __angularViActualMod2;

Requirements:

  • Must mock full implementation (not only metadata) for any modules, as vi.mock() does
  • Must stub components, services, modules, pipes, directives both metadata and implementation
  • Must preserve ESM live bindings semantics
  • Must preserve sourcemaps and coverage
  • Must not require runtime module loader

Alternatives considered

Currently we have no choice, but stay with slow and inefficient jest + jest-preset-angular.

I've implemented deep-automocking infrastructure for jest.mock() ng-automocks-jest, it can stub any angular entities, both metadata and implementation.

Reacted by HerrDerb, gcoadour, Arnaud Mouronval, TatyanaKonina, Pavel Biryuchev, Alexander, Alex Inkin, Lyudmila Kovtun, Nezar Khamidekh, Sam Bulatov and 20 more

Activity

  1. angular-robot
    added
    gemini-triagedLabel noting that an issue has been triaged by geminiLabel noting that an issue has been triaged by gemini
    on Mar 2, 2026
  2. ngbot
    added this to the needsTriage milestone on Mar 2, 2026
  3. HerrDerb commented on Mar 2, 2026

    @HerrDerb
    HerrDerb
    on Mar 2, 2026
    More actions

    I did run into the same issue. I did mock an import (import { jwtDecode } from 'jwt-decode';) for test which now does not work anymore.

    vi.mock('jwt-decode', () => ({
      jwtDecode: vi.fn(),
    }));
    
    
    it(...){
      //...
        (jwtDecode as ReturnType<typeof vi.fn>).mockReturnValue({
          realm_access: {
            roles: ['admin', 'user'],
          },
        });
      //...
    
    }
    
  4. JeanMeche
    added
    gemini-triagedLabel noting that an issue has been triaged by geminiLabel noting that an issue has been triaged by gemini
    on Mar 2, 2026
  5. JeanMeche
    transferred this issue fromangular/angularon Mar 2, 2026
  6. alan-agius4
    added
    action: cleanupThe PR is in need of cleanup, either due to needing a rebase or in response to comments from reviewsThe PR is in need of cleanup, either due to needing a rebase or in response to comments from reviews
    area: @angular/build
    angular/build:unit-test
    and removed
    gemini-triagedLabel noting that an issue has been triaged by geminiLabel noting that an issue has been triaged by gemini
    action: cleanupThe PR is in need of cleanup, either due to needing a rebase or in response to comments from reviewsThe PR is in need of cleanup, either due to needing a rebase or in response to comments from reviews
    on Mar 2, 2026
  7. gcoadour commented on Mar 2, 2026

    @gcoadour
    gcoadour
    on Mar 2, 2026
    More actions

    Related to #31609

  8. clydin
    linked a pull request that will close this issuefix(@angular/build): conditionally allow `vi.mock` for non-relative imports #32655on Mar 3, 2026
  9. MillerSvt commented on Mar 4, 2026

    @MillerSvt
    MillerSvt
    on Mar 4, 2026
    Author
    More actions

    @alan-agius4 let's continue here.

    Instead TestBed.overrideProvider or TestBed.configureTestingModule should be used as is the supported way

    TestBed is not enough to mocking. As described here, it cannot mock implementation. It can only override metadata. Also TestBed cannot mock platform providers, but only root providers.

    If you want to stay framework agnostic, please allow us to add esbuild plugin to implement this thing by third-party plugin. We need to intercept vi.mock and related calls at compile-time, and transform it for tests bundle. I can create ng-automocks-vitest plugin and implement this mocks on my own.

    Reacted by Ramiro Jr. Franco, Jaime Burgos, Ilya Borisov, Maciej Niedzielski, Diandson C. Ramos and VeselyT
  10. clydin
    removed a link to a pull requestfix(@angular/build): conditionally allow `vi.mock` for non-relative imports #32655on Mar 4, 2026
  11. MillerSvt commented on May 28, 2026

    @MillerSvt
    MillerSvt
    on May 28, 2026
    Author
    More actions

    Can I try to make pull request for this to push it forward?

    Reacted by HerrDerb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    angular/build:unit-testarea: @angular/build

    Type

    No type

    Projects

    No projects

      Milestone

      • needsTriageNo due date

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      You are visitor 01402520 — GeezerVison does not store the pages you look up.
      Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.