如何在服务中测试JSONP方法-Angular

问题描述 投票:2回答:2

我正在编写一个简单的电子邮件订阅应用程序,为此我已经编写了测试,并且到目前为止一切正常。

为了简单起见,我想解释一下我所面对的问题的确切部分。

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')
  }

}

以上是调用api的服务中的简单方法

链接到服务文件:https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.ts

现在我正尝试为上述方法submitForm中的一个编写测试用例

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);
  });

此规范文件的链接:https://stackblitz.com/edit/angular-testing-imniaf?file=app%2Fmy-service.spec.ts

这是我被卡住的地方,上面的代码将错误抛出为,

错误:期望一个符合条件的匹配请求“按功能匹配:“,一无所获。

完整的可工作stackblitz链接:

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

请帮助我成功通过此测试。

javascript angular typescript unit-testing karma-jasmine
2个回答
0
投票

HttpClient应该是间谍,然后可以对其进行断言。

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

然后在测试中

  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('[email protected]');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith(provideValueHere, 'c');
  });

现在您的测试应该是这样的:

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('[email protected]');
    expect(actual).toBe(expected);
    expect(httpClient.jsonp).toHaveBeenCalledWith('https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55&[email protected]&subscribe=Subscribe&b_aaa7182511d7bd278fb9d510d_01681f1b55=', 'c');
  });
});

0
投票

看看working demo code here

  1. 您应该删除useClass:)

  2. 更正的mailChimpEndpoint值。

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

  4. 已删除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);
  });
© www.soinside.com 2019 - 2024. All rights reserved.