简体   繁体   English

如何在Angular中测试JSONP HTTP请求?

[英]How do I test a JSONP HTTP request in Angular?

I'm using the HttpClientModule and HttpClientJsonpModule to make a JSONP HTTP request in a service. 我正在使用HttpClientModuleHttpClientJsonpModule在服务中发出JSONP HTTP请求。

app.module.ts app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HttpClientJsonpModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    HttpClientJsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This service uses the jsonp method from the HttpClient class to get a JSONP response from the specified URL. 此服务使用HttpClient类中jsonp方法从指定的URL获取JSONP响应。 I think that this response is intercepted by JsonpInterceptor and sent to the JsonpClientBackend where the request is handled. 我认为此响应被JsonpInterceptor拦截, 并发送到处理请求的JsonpClientBackend

example.service.ts example.service.ts

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

@Injectable()
export class ExampleService {
  url = "https://archive.org/index.php?output=json&callback=callback";

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.jsonp(this.url, 'callback');
  }
}

Using the HttpClientTestingModule , I inject the HttpTestingController so I can mock and flush my JSONP HTTP request. 使用HttpClientTestingModule ,我注入HttpTestingController,以便可以模拟和刷新JSONP HTTP请求。

example.service.spec.ts example.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import { 
  HttpClientTestingModule,
  HttpTestingController
} from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ExampleService]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });

      const req = httpMock.expectOne(service.url); // Error
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});

In the end, I get the error 最后,我得到了错误

Error: Expected one matching request for criteria "Match URL: https://archive.org/index.php?output=json&callback=callback", found none.

If I change the request method to GET, this test works as expected. 如果我将请求方法更改为GET,则此测试将按预期工作。

From what I can tell, the HttpClientTestingModule uses the HttpClientTestingBackend but there is no JsonpClientTestingBackend or corresponding interceptor. 据我所知,HttpClientTestingModule使用HttpClientTestingBackend,但是没有JsonpClientTestingBackend或相应的拦截器。

How do I test a JSONP HTTP request in Angular? 如何在Angular中测试JSONP HTTP请求?

According to an Angular developer this is a bug . 根据Angular开发人员的说法,这是一个错误 Here's a workaround for now. 这是目前的解决方法。

example.service.spec.ts example.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
// Import the HttpClientJsonpModule, HttpBackend, and JsonpClientBackend
import { HttpClientJsonpModule, HttpBackend, JsonpClientBackend } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ExampleService } from './example.service';

describe('ExampleService', () => {
  let service: ExampleService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      // Use the HttpBackend instead of the JsonpClientBackend
      providers: [ExampleService, { provide: JsonpClientBackend, useExisting: HttpBackend }]
    });

    service = TestBed.get(ExampleService);
    httpMock = TestBed.get(HttpTestingController);
  });

  describe('#getData', () => {
    it('should return an Observable<any>', () => {
      const dummyData = { id: 1 };

      service.getData().subscribe(data => {
        expect(data).toEqual(dummyData);
      });
      // Pass a function to the expectOne method
      const req = httpMock.expectOne(request => request.url === service.url);
      expect(req.request.method).toBe('JSONP');
      req.flush(dummyData);
    });
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM