How to test a JSONP method in a service - Angular

≯℡__Kan透↙ 提交于 2020-06-13 07:00:37

问题


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('test@gmail.com').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.


回答1:


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('test@gmail.com').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);
  });



回答2:


HttpClient should be a spy, then you can assert it.

TestBed.configureTestingModule({
  // add this to the definition of the testing module
  providers: [{
    provide: HttpClient,
    useValue: {
      jsonp: jasmine.createSpy('httpClient.jsonp'),
    }
  }]
})

and then in the test

  it('check subscribeEmail function has been called in service', (done: DoneFn) => {
    const service = TestBed.get(MyService);
    const httpClient = TestBed.get(HttpClient);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith(provideValueHere, 'c');
  });

and now your test should be like that:

import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';

import { MyService } from './my-service';

describe('MyService', () => {
  beforeEach(() => TestBed.configureTestingModule({
      providers: [
        MyService,
        {
          provide: HttpClient,
          useValue: {
            jsonp: jasmine.createSpy('httpClient.jsonp'),
          }
        }
      ]
    }).compileComponents());

  it('check subscribeEmail function has been called in service', () => {
    const httpClient = TestBed.get(HttpClient);
    const service = TestBed.get(MyService);

    const expected: any = Symbol();
    (httpClient.jsonp as any).and.returnValue(expected);

    const actual = service.submitForm('test@gmail.com');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith('https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55&ampEMAIL=test@gmail.com&subscribe=Subscribe&b_aaa7182511d7bd278fb9d510d_01681f1b55=', 'c');
  });
});


来源:https://stackoverflow.com/questions/62167637/how-to-test-a-jsonp-method-in-a-service-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!