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:
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);});
- Infer the type of the return value
type ReturnType = jasmine.Spy;declare module 'ts-auto-mock/extension' {interface Method<TR> extends ReturnType {}}
Method Usage
- Create an interface
interface Interface {methodToSpy: () => string}
- Create a mock
const mock: Interface = createMock<Interface>();
Get the spy from the method.
You can extract the method being spied in two different ways.
- 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));
- Or, directly as string:import { On, method } from "ts-auto-mock/extension";const spy: jasmine.Spy = On(mock).get(method('methodToSpy'));
- Through a callback function that accesses the mock:
Trigger the method and perform your assertions
someMethodThatWillTriggerInterfaceA();expect(spy).toHaveBeenCalled();