TS auto mock
HomeInstallationCreate mockCreate mock listCreate hydrated mockRegister mockExtensionCustom MethodTypes supportedTypes not supportedConfigPerformanceDefinitely TypedLocal development

Extension

To preserve type safety, we utilize the capability of the type checker to infer types through external interfaces, which enables us to easily inject spies from various testing frameworks without having to perform implicit type casts.

If you need custom spies you can use our framework to wrap- and later extract them.

Custom Method

This example is taken from: jasmine-ts-auto-mock

To extend a method you need to:

  1. Create your spy function (jasmine.createSpy(name))

    Please note that the value returned from provideMethodWithDeferredValue must be a function.

    Therefore, you will need to make sure that the method you are providing will not execute the function directly, otherwise it will cause an infinite recursion and crash the application almost immediately, once it exceeds the allowed call stack size.

    In the example below, the function to be spied upon is passed into callFake which will prevent the function from being executed directly.

import { Provider } from "ts-auto-mock/extension";
Provider.instance.provideMethodWithDeferredValue((name: string, value: () => any) => {
return jasmine.createSpy(name).and.callFake(value);
});
  1. Infer the type of the return value
type ReturnType = jasmine.Spy;
declare module 'ts-auto-mock/extension' {
interface Method<TR> extends ReturnType {}
}

Method Usage

  1. Create an interface
interface Interface {
methodToSpy: () => string
}
  1. Create a mock
const mock: Interface = createMock<Interface>();
  1. Get the spy from the method.

    You can extract the method being spied in two different ways.

    1. Through a callback function that accesses the mock:
      import { On, method } from "ts-auto-mock/extension";
      const spy: jasmine.Spy = On(mock).get(method(mock => mock.methodToSpy));
    2. Or, directly as string:
      import { On, method } from "ts-auto-mock/extension";
      const spy: jasmine.Spy = On(mock).get(method('methodToSpy'));
  2. Trigger the method and perform your assertions

someMethodThatWillTriggerInterfaceA();
expect(spy).toHaveBeenCalled();