Mock Dependencies in a TypeScript Unit Test

Last modified by Vincent Massol on 2026/11/17 19:57

Steps

Replace the dependencies of the code under test with typed mocks in a Vitest unit test, as recommended for the Front-End Test packages.

  1. Add the library to the package pnpm add -D vitest-mock-extended
  2. Import mock in the test import { mock } from "vitest-mock-extended";
  3. Create a mock of the dependency, with an optional partial implementation
    import { EntityType } from "@xwiki/platform-model-api";
    import type { DocumentReference } from "@xwiki/platform-model-api";
    
    // The mock is typed MockProxy<DocumentReference> & DocumentReference: no cast is needed.
    const sourceDocument = mock<DocumentReference>({
      type: EntityType.DOCUMENT,
      name: "Source",
    });
  4. Stub a return value for specific arguments with calledWith on the method
    import type { DocumentService } from "@xwiki/platform-document-api";
    import type { Container } from "inversify";
    
    const documentService = mock<DocumentService>();
    const container = mock<Container>();
    
    container.get.calledWith("DocumentService").mockReturnValue(documentService);
  5. Throw on a service id that has no stub with fallbackMockImplementation on the Container mock
    const container = mock<Container>(
      {},
      {
        fallbackMockImplementation: (id: unknown) => {
          throw new Error(`Unexpected service: ${String(id)}`);
        },
      },
    );
  6. Declare a mock shared by the tests of a suite as MockProxy, create it in beforeEach and reset it with mockReset
    import { beforeEach } from "vitest";
    import { mock, mockReset } from "vitest-mock-extended";
    import type { MockProxy } from "vitest-mock-extended";
    
    let documentService: MockProxy<DocumentService>;
    
    beforeEach(() => {
      documentService = mock<DocumentService>();
    });
    
    // A mock created once for the whole file is reset instead.
    const serializer = mock<RemoteURLSerializer>();
    beforeEach(() => {
      mockReset(serializer);
    });
  7. Stub get of a provider to return a mock when the code under test calls provider.get().method()
    import type {
      RemoteURLSerializer,
      RemoteURLSerializerProvider,
    } from "@xwiki/platform-model-remote-url-api";
    
    const serializer = mock<RemoteURLSerializer>();
    serializer.serialize.mockReturnValue("/download/my/page/cat.png");
    const provider = mock<RemoteURLSerializerProvider>();
    provider.get.mockReturnValue(serializer);
  8. Run the tests pnpm vitest run The tests pass. A lookup of a service without a stub fails at once, at the line of the lookup, with the message below.
    Error: Unexpected service: DocumentService

FAQ

Which matchers can calledWith take?

Use any(), anyObject() or matches(predicate) in place of a literal argument.

Why not stub with an object literal cast as unknown as T?

The cast turns off type checking of the stub, so a member it lacks, or one renamed in T, only fails when the test runs. mock<T>() needs no cast, so the compiler checks every member the test sets.

Why make the Container mock throw?

Without fallbackMockImplementation an unstubbed lookup returns undefined and the test fails later, far from the cause. Throwing makes it fail at the lookup.

Which mocks must not get a fallbackMockImplementation?

A mock that Vue receives as a prop or that gets stringified: the fallback runs on every unstubbed call, toString included, so those throw too.

Why does mockDeep not help with provider.get().method?

get() returns undefined unless its return value is stubbed, and funcPropSupport only provides get.method. Stub get to return a mock<X>() instead.

Related

Get Connected