Ad

How To Test A JSONP Method In A Service - Angular

I am making a simple email subscription application for which I have written tests and things went fine as for now.

In order to make things simple, I wish to explain the exact part where I am facing the issue.

my-service.ts :

export class MyService {

  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp';

  constructor(private _http: HttpClient) {}

  submitForm(email: string){

        const params = new HttpParams()

        .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')

        const mailChimpUrl = this.mailChimpEndpoint + params.toString();

        return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }

}

The above is a simple method in a service that calls an api

Link to the service file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.ts

Now I am trying to write a test case for the above method submitForm in

my-service.spec.ts

  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    service.submitForm('[email protected]').subscribe(
        response => {
            expect(response).toEqual(mockServiceData);
        }
    )

    const reqMock = httpTestingController.expectOne(request => request.url === mailChimpEndpoint);
    expect(reqMock.request.method).toBe('GET');
    reqMock.flush(mockServiceData);
  });

Link to this spec file: https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.spec.ts

This is where I am getting stucked and the above code throws the error as,

Error: Expected one matching request for criteria "Match by function: ", found none.

The complete working stackblitz link:

https://stackblitz.com/edit/angular-testing-ajoov8

Please help me to pass this test as success.

Ad

Answer

Take a look at working demo code here

  1. You should have removed useClass :)

  2. Corrected mailChimpEndpoint value.

  3. corrected expect(reqMock.request.method).toBe('JSONP');

  4. Removed done: DoneFn.

  it('check subscribeEmail function has been called in service', () => {
    const service = TestBed.get(MyService);
    service.submitForm('[email protected]').subscribe(
        response => {
            console.log(response)
            expect(response).toEqual(mockServiceData);
        }
    )

    const reqMock = httpTestingController.expectOne(req => req.url === mailChimpEndpoint);
    expect(reqMock.request.method).toBe('JSONP');
    reqMock.flush(mockServiceData);
  });
Ad
source: stackoverflow.com
Ad