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

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

我正在做一个简单的电子邮件订阅应用程序,我已经写了测试,目前一切正常。

为了使事情简单化,我想解释一下我所面临的问题的具体部分。

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.comeditangular-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.comeditangular-testing-imniaf?file=app%2Fmy-service.spec.ts。

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

错误。预期有一个匹配的请求,条件是 "通过函数匹配,",没有找到。 ",没有找到。

完整工作的stackblitz链接。

https:/stackblitz.comeditangular-testing-ajoov8。

请帮助我成功通过这个测试。

angular typescript unit-testing jasmine karma-jasmine
1个回答
1
投票

看一看 工作演示代码在这里

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

1
投票

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