Search code examples
angularunit-testingsubscriptionsubscribe

If i add subscribe in service and unit test of that service, i'm getting Property 'subscribe' does not exist on type 'Subscription'?


This is my service

my-service.service.ts

export class MyService {
    constructor(public http: HttpClient) {}

    createChatRecord (data, id) {
        let logData = {"hist" : data , "uid": id };
        let headers = new HttpHeaders();
        headers = headers.set("Content-Type", "application/json");
        let options = { headers: headers };

        return this.http.post(MY_URL, logData, options)
            .subscribe(res => res);

    }
}

This is my spec file for the above service

my-service.spec.ts

it("It should post", () => {
        myservice.createChatRecord(mockData, mockId)
            .subscribe((data: any) => {
            expect(data).toBe(null);
        });
    const mockReq = httpMock.expectOne(MY_URL);
    expect(mockReq.request.method).toBe("POST");
    mockReq.flush(null);
    httpMock.verify();
});

If i add subscribe in spec file, i'm getting this error. Property 'subscribe' does not exist on type 'Subscription'. But if i remove subscribe in service, it is not showing that error.

I need to use subscribe in my service. How can i test this post call without this error ?

Any help would be appreciated!


Solution

  • You incorrectly have the subscribe() usage in your service class. If you remove that usage you will get rid of that error.

    createChatRecord (data, id) {
        let logData = {"hist" : data , "uid": id };
        let headers = new HttpHeaders();
        headers = headers.set("Content-Type", "application/json");
        let options = { headers: headers };
    
        return this.http.post(MY_URL, logData, options);
    
    }