Pritam Bohra
Pritam Bohra

Reputation: 4319

Testing a RxJS Subject: subscribe method not getting called in the test

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

Answers (1)

nash11
nash11

Reputation: 8650

There are two issues with your code.

  1. 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.
  2. The expectation will now be executed but the test will fail since the data is passed incorrectly. 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

Related Questions