testing/src/user.mock.ts
Mock class of the StarkUserService interface.
SpyObj
Properties |
|
Public fetchUserProfile |
Type : Spy<>
|
Default value : jasmine.createSpy("fetchUserProfile")
|
Defined in testing/src/user.mock.ts:12
|
See StarkUserService fetchUserProfile() method |
Public getAllUsers |
Type : Spy<>
|
Default value : jasmine.createSpy("getAllUsers")
|
Defined in testing/src/user.mock.ts:17
|
See StarkUserService getAllUsers() method |
The mock class MockStarkUserService
can be imported as follows:
import { MockStarkUserService } from "@nationalbankbelgium/stark-core/testing";
Since the mock class implements the base interface of the service it mocks, you just need to provide the mock in your TestingModule
:
TestBed.configureTestingModule({
imports: [...],
declarations: [...],
providers: [
...
{ provide: STARK_USER_SERVICE, useValue: new MockStarkUserService() },
...
]
});
Then you can just inject the Stark service via the TestBed using its corresponding InjectionToken
:
// this will inject the instantiated mock class
mockUserService = TestBed.inject(STARK_USER_SERVICE);
In fact, every method of the base interface is simply mocked with a Jasmine Spy which can then be used in the unit tests to:
For example:
Example :// returning custom value
mockUserService.fetchUserProfile.and.returnValue(of(someUser));
// overriding a method with a custom function
mockUserService.fetchUserProfile.and.callFake(() => {
// some custom logic to return a specific value
});
// asserting that a method was indeed called
expect(mockUserService.fetchUserProfile).toHaveBeenCalledTimes(1);
import { StarkUserService } from "@nationalbankbelgium/stark-core";
import Spy = jasmine.Spy;
import SpyObj = jasmine.SpyObj;
/**
* Mock class of the {@link StarkUserService} interface.
*/
export class MockStarkUserService implements SpyObj<StarkUserService> {
/**
* See [StarkUserService fetchUserProfile()]{@link StarkUserService#fetchUserProfile} method
*/
public fetchUserProfile: Spy<StarkUserService["fetchUserProfile"]> = jasmine.createSpy("fetchUserProfile");
/**
* See [StarkUserService getAllUsers()]{@link StarkUserService#getAllUsers} method
*/
public getAllUsers: Spy<StarkUserService["getAllUsers"]> = jasmine.createSpy("getAllUsers");
}