Mohammad Ashfaq
Mohammad Ashfaq

Reputation: 147

How to get coverage for mocked methods in Jasmine for Angular7 Promises

Jasmine test for angular 7 service which returns a Promise object is not reflecting in code coverage.

@Injectable()
export class MyService {
constructor(private http:HttpClient,private httpService: HttpService) { 
}

getAllRecords (requestData: MyRequest): Promise<MyResponse> {
    return new Promise((resolve, reject) => {
        let url:string = `${ApiUrl.getUrl}`;
        this.httpService.makeHttpGetRequest(url, requestData)
        .subscribe((response) => {
            resolve(response.body);
        }, (error) => {
            reject();
        });
    });
}
}

Test

describe('MyService', function () {
let myService: MyService;
it('getAllRecords should have been called and return all records', (done) => {
        const spy = spyOn(myService, 'getAllRecords').and.returnValue(Promise.resolve({ id: 1 }));

        myService.getAllRecords(null);
        spy.calls.mostRecent().returnValue.then(() => {


            expect(myService.getAllRecords).toHaveBeenCalledWith(null);
            done();
        });
    })
})

Test is passing but does not reflect in code coverage report created using Istanbul, commenting test has not reflect on code coverage percentage.

Upvotes: 0

Views: 47

Answers (1)

dmcgrandle
dmcgrandle

Reputation: 6060

You are stubbing the method when you declare:

const spy = spyOn(myService, 'getAllRecords').and.returnValue(Promise.resolve({ id: 1 }));

The method itself will never be entered into, because your spy returns a different value on it's behalf.

I would suggest that rather than setting the spy on myService.getAllRecords(), you instead set a spy on httpService.makeHttpGetRequest() and return a cold observable that completes immediately with various values to test for both the happy path and the error case.

Upvotes: 1

Related Questions