Typescript Mocking Framework (using Jasmine)
Create Type-Safe Mock objects for Typescript Classes and Interfaces Jasmine Spy is automatically created when mocking a method so it is still possible to use verification methods like toHaveBeenCalled().
How to use
Basics
Initializing and setting up a new Mock object can be done in several ways:
// 1. Use the constructor with Partial<T> which is great // because you can use an object with all the setup you want mockCookieService = <CookieService> `customized `; // 2. Use the 'extend()' method with Partial<T>. // With the extend method it is possible to override settings during tests mockCookieService = <CookieService>; mockCookieService // 3. If you like fluent interface use the 'setup() / is()' methods. // The setup method is great for properties or methods that should be available // during you test, but do not need an implementation for the test to run. mockCookieService = <CookieService>; mockCookieService; // 3a. Setup the return value can be done using the is() method. mockCookiesService ; // 3b. You can also chain setup/is combinations like mockCookieService ; // 4. Get the jasmine calls object for a specific method let countsOfGet = mockCookieService ; // 5. Reset the calls of the specific method mockCookieService ;
Generic methods
When mocking generic methods the is()
method can not determine the return type because you use the service in your application with a specified type. Let say you have a service with the following interface:
In your application you use the service to returns users:
... someServiceget<User>10 ...
If you would like to mock this in you unit test normally you would write:
mockSomeService ; // or mockSomeService ;
Unfortunately typescript will complain about the fact that of(someUser)
is not of type Observable<T>
:
Type 'Observable<User>' is not assignable to type 'Observable<T>'.
Type 'User' is not assignable to type 'T'.
Now the as<T>()
comes into the rescue. With this method you can overrule the return value that is automatically determined by the setup() method.
Note: Please note that this can conflict with the real code if not used appropriately, so use at your own risc
mockSomeService as< Observable<User>> ; // Or if not using the 'value' argument mockSomeService as< Observable<User>> ;
With this typescript will not complain anymore. Great! ;-)
Dummy methods
If in your tests the method should be available but the output does not matter you can use the
Mock.ANY_FUNC
constant.
// using the Mock.ANY_FUNC mockCookieService = <CookieService> put: MockANY_FUNC; // or mockCookieService; // or mockCookieService;
setup()
and extend()
Mixing It is also possible to mix the usage of extend()
and setup()
methods.
// when using the setup method it is still possible to define the implementation // with both 'is()' method as the extend method mockCookieService; mockCookieService;
Static methods
// Mocking static methods is possible using the Mock.static method // class Foo { // static bar(): string { // return 'bar'; // } // } Mock;
Why did I create this library?
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 your original class changes you have to change all the Mock classes as well, but there is no intellisense for this. With this framework it is possible to create Mock objects with intellisense and possibility to override methods during your tests and even by type-safe!!!
// 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; ;
In your test you can define other behavior using the 'extend' method of the Mock or using the 'setup' and 'is' methods.
; ; ;
Every method that is mocked using 'extend' or 'setup' is automatically spied using jasmine.Spy. So it is possible to use 'expect().toHaveBeenCalled' methods etc. Therefor it is not needed any more to use the jasmine.Spy object directly for mocking behavior. ts-mocks helps you to be type-safe (so use that ;-))
;
If for some reason you still want the original jasmine.Spy object (just Don't ;-)). You can use the spyOf() method of the mock. Be aware that you type-safety is gone.
;
Using TestBed with Ts-mocks
It you want to use TestBed in combination with ts-mock you should be aware to use the correct provider.
In most examples you will see the use of useValue as provider type
let mockService: Mock<SubService>; let systemUnderTest: MainService; ; ;
This will work if you don't want to change the behavior of the mock during your test. If you still want to change the behavior like example below this will not work. This is because useValue creates a copy of the object injected, so this is not the same object as the mockService member.
;
Solution for TestBed
The solution for this is not to use useValue but use useFactory which is a method that is called by the DI container every time the service needs to be injected. useFactory is used like so:
let mockService: Mock<SubService>; let systemUnderTest: MainService; ; ;
When you now want to change the behavior during your test this is possible:
;
A note on setup() and spyOf() methods
Some test environments (for example, Wallaby.js) might be incompatible with ts-mocks
library because these methods use dynamic property name inferring under the hood. In such cases you can try set the property name manually:
mockCookieService // also possible mockCookieService
Make sure that the property that your lambda cs => cs.get
returns and the property name 'get'
in the second argument are the same, otherwise the type safety might be broken.
A note on using other frameworks then Jasmine
If you are using other framework like Jest instead of Jasmine. Have a look at https://github.com/ike18t/ts-mockery.