The goal you are aiming for is Integration testing as you seek to test the collaboration between two units (AppComponent
and SortService
).
Since you are focusing on unit testing, it seems like you intend to test the AppComponent
class. This implies that any injectable dependency used in AppComponent
must be mocked, such as the SortService
class. Two methods can accomplish this.
Approach 1: Using a Mock class for SortService
.
app.component.spec.ts
// Mock the SortService class, its method and return it with mock data
class MockSortService extends SortService{
getSortData(data, rendererKey, type) {
return [someRandomArray];
}
}
beforeEach(async( () => {
TestBed.configureTestingModule({
providers: [
// Utilize Angular DI by providing the following provider to replace SortService with MockSortService in the injector
{ provide: SortService, useClass: MockSortService },
]
});
));
Approach 2: Using a Spy object.
app.component.spec.ts
beforeEach(async( () => {
// Create jasmine spy object
sortServiceSpy = jasmine.createSpyObj('SortService', 'sortNumberData');
// Provide the dummy/mock data to sortNumberData method.
sortServiceSpy.sortNumberData.returnValue([someRandomArray]);
TestBed.configureTestingModule({
providers: [
{ provide: SortService, useValue: sortServiceSpy},
]
});
));
I personally prefer approach 2 for its simplicity and elegance, but either of the two approaches can be used.
I hope this information proves helpful!