Typescript Mocking Framework
Create Mock objects for Typescript Classes and Interfaces
Jasmine Spy is automatically created during setup method
Example:
// Mock for the CookieService from angular2-cookie mockCookieService = <CookieService>; mockCookieService; mockCookieService;
Why?
When creating Unit Tests with Typescript / Angular most of the examples on the internet use a Mock class that must be created. A Mock class looks like this:
// Mocks the CookieService from angular2-cookie public : string return null; public { }
The Mock class is used directly or injected by the TestBase.configureTestingModule method.
let cookiesService: CookieService; // Add the providers; // Inject values;
This works 'Okay' but there is no real intellisense for you when you are mocking your objects.
This Mock class must have the same methods as the class to Mock otherwise your test will not work. First time
creation is not so hard, but when you original class changes you have to change all the Mock classes aswell, but there
is intellisense for this. With this framework it is possible to create Mock objects with intellisense and possibility to
override methods during your tests.
// Create a variable for the Mock<T> classlet mockCookiesService: Mock<CookieService>;let cookieService: CookieService; // NOTE: Change the useClass to useValue and use the ;
You don't need to use the TestBed setup if you don't want to. Creating Mocks is not related to the TestBed. The following is also possible:
let sut: MyOwnService; ;
Basically there are two properties and methods on typscript object that you can Mock like so:
// Property mocking, where someValue must be of the same type as the property mockService; // Method mocking, where the is() defines the new body of the method mockService;
In your test you can define other behavior using the 'setup' method of the Mock
; ;
If you need to change the spy during your unit test you can use the Spy object returned by the setup() / is() methods. But most of the unit test do not need the spy directly.
;