I have two components and a service layer. The service layer has a subject declared in it with a set and get method definition. The first component, based on an user action calls the set method of the subject while the second component is subscribed to the same subject. It works just fine but when I try to unit test the subscription in second component, I'm having trouble with the approach. I have a mock service layer created to test other functionalities as well.
The subscription inside ngOnit is not getting hit during the test run. Code executes within the subscribe when component initializes but not after setSubject is invoked. When I debug, I can see that it hits after the execution is complete but I have no way to verify if data is updated.
export class MockService {
private subject = new Subject<any>();
getSubject() {
return Observable.of(this.subject);
}
setSubject(value) {
this.subject.next({ message: value });
}
}
Component 2
export class Component2 implements OnInit {
textFromComponent1: string;
subscription: Subscription;
constructor(public service: Service) {}
ngOnInit() {
this.subscription = this.service.getSubject().subscribe(message => {
this.textFromComponent1 = message.value;
});
}
}
Component 2 Unit Test
beforeEach( async(() => {
TestBed.configureTestingModule( {
declarations: [Component2],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [{ provide: Service, useClass: MockService }]
} )
.compileComponents();
} ) );
beforeEach(() => {
fixture = TestBed.createComponent( Component2 );
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should test subscription' () => {
component.service.setSubject("abc");
expect(component.textFromComponent1).toBe("abc");
});
