Reputation: 4319
I have a private Subject
attributeNameSubject. There is a setAttributeName method that passes a string value to the subject. We get reference to that subject using the getAttributeName. I am trying to test the above code, but I always get false-positive, i.e. the test passes but I get test has no expectation warning. Turns out it is not calling the subscribe method at all.
I am testing this code in Angular 7.
private readonly attributeNameSubject = new Subject<string>();
get getAttributeName(): Subject<string> {
return this.attributeNameSubject;
}
setAttributeName(value: any) {
this.getAttributeName.next(value.attributeName);
}
it('should set attribute name on valid input', () => {
service = TestBed.get(AttributeService);
service.setAttributeName('some random string');
service.getAttributeName.subscribe((data: string) => {
expect(data).toEqual('some random string');
});
});
Upvotes: 1
Views: 1936
Reputation: 8650
There are two issues with your code.
setAttributeName
emits the value to the subscribers while getAttributeName
listens to the observable. So when you call setAttributeName
, getAttributeName
emits a value but there is nothing subscribed to it. So you should first subscribe to getAttributeName
and then call setAttributeName
to emit the value.getAttributeName
emits value.attributeName
while you are just passing a string. You need to instead pass an object.Here's the working test case.
it('should set attribute name on valid input', () => {
service = TestBed.get(AttributeService);
service.getAttributeName.subscribe((data: string) => {
expect(data).toEqual('some random string');
});
service.setAttributeName({ attributeName: 'some random string' });
});
Upvotes: 2