I am doing a Unit Test on one of the methods of component in my angular 10 project
and I saw this code:
MessageListComponent.ts
EDIT: updating the complete code (the answer is already in the comment of this post)
@Component({
selector: 'app-message-list',
template: ...,
providers: [
MessageService
]
})
export class MessageListComponent {
constructor(private messageService: MessageService) {}
ngOnInit() {
// other implementation
....
this.GetAllContents();
}
GetAllContents() {
if(this.subscribedMessage) {
this.subscribedMessage.unsubscribe();
}
this.subscribedMessage = this.messageService.getAllContents().subscribe((data) => {
data && data.forEach(item => this.dataList.push(item));
// further codes here
...
},
() => {
// further codes here
...
});
// further codes here
...
}
}
and I created a spec file like so:
MessageListComponent.spec.ts
describe('MessageListComponent', () => {
let fixture: ComponentFixture<MessageListComponent>;
let component: MessageListComponent;
let messageService: MessageService;
beforeEach(() => {
// TestBed configuration
TestBed.configureTestingModule({
....
providers: [
MessageService,
....
]
}).compileComponents();
});
beforeEach(() => {
messageService = TestBed.inject(MessageService);
messageService.getAllContents = jasmine.createSpy().and.returnValue(observableOf(<any[]>[{}]));
fixture = TestBed.createComponent(MessageListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should load', () => {
expect(messageService.getAllContents).toHaveBeenCalled();
});
});
when I run the ng test --code-coverage=true
the coverage got the implementation inside GetAllContents method of MessageListComponent but the function inside the subscribe method is not getting covered by the coverage
Is there something I'm missing to get the function inside the subscribe method?