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

时间:2017-12-07 21:13:38

标签: javascript angular unit-testing http jsonp

我正在使用HttpClientModuleHttpClientJsonpModule在服务中发出JSONP HTTP请求。

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 { }

此服务使用jsonp中的HttpClient class方法从指定的URL获取JSONP响应。我认为此回复被JsonpInterceptor拦截并发送到处理请求的JsonpClientBackend

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

使用HttpClientTestingModule,我注入HttpTestingController,这样我就可以模拟并刷新我的JSONP HTTP请求。

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

最后,我收到了错误

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

如果我将请求方法更改为GET,则此测试按预期工作。

据我所知,HttpClientTestingModule使用HttpClientTestingBackend,但没有JsonpClientTestingBackend或相应的拦截器。

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

1 个答案:

答案 0 :(得分:4)

根据Angular开发人员的说法,这是a bug。这是现在的解决方法。

<强> example.service.spec.ts

class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * One User can have many social networks
     * @ORM\OneToMany(targetEntity="UserInSocialNetworks", mappedBy="user", cascade={"remove"})
     */
    private $socialnetworks;