I've been trying to unit test the subscribe function of this service. And looking at the code coverage report generated by istanbul, I can see that this code is not covered.
Code
layout.component.ts
import {Component, HostListener, Input} from '@angular/core';
import { LayoutService } from './layout.service';
import { some } from 'lodash';
@Component({
selector: 'cgm-layout',
templateUrl: './layout.component.html',
styleUrls: ['./layout.component.scss'],
providers: [LayoutService]
})
class LayoutComponent {
message: any;
constructor(
private service: LayoutService
) {
service.messagePublished$.subscribe(
message => {
this.setMessage(message);
}
);
}
setMessage(message): void {
this.message = message;
setTimeout(() => {
this.message = null;
}, 7000);
}
}
export {
LayoutComponent
};
This is my Unit Test
layout.component.spec.ts
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { of } from 'rxjs';
import { LayoutComponent } from './layout.component';
import { LayoutService } from './layout.service';
describe('LayoutComponent', () => {
let component: LayoutComponent;
let fixture: ComponentFixture<LayoutComponent>;
let service;
beforeEach(async(() => {
service = new LayoutService();
mockLayoutService = jasmine.createSpyObj('LayoutService', ['messagePublished$']);
TestBed.configureTestingModule({
declarations: [
LayoutComponent,
],
providers: [
LayoutService
],
schemas: [
NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LayoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
component.message = 'Garbage';
});
it('should call messagePublished', () => {
spyOn(service.messagePublished$, 'subscribe');
TestBed.createComponent(LayoutComponent);
expect(service.messagePublished$.subscribe).toHaveBeenCalled();
});
describe('setMessage', () => {
it('should set the Message', fakeAsync(() => {
component.setMessage('Message');
expect(component.message).toBe('Message');
tick(7000);
expect(component.message).toBeNull();
}));
});
});
So the code never seems to go over the 'service.messagePublished$.subscribe' part. Here is the code coverage report.
The error I'm getting is 'Expected spy subscribe to have been called', which I'm guessing is the error you get when that code block is not covered.