如何模拟进行AJAX调用的方法?

时间:2017-11-08 14:32:55

标签: javascript ajax angular unit-testing karma-jasmine

我正在尝试为我的Angular应用程序编写一些测试,并且我想模拟一个方法,这样我就不会对服务器进行实际调用。

这是我的grid.service.ts中的方法:

     loadAccountListPromise(id: string) {
        let promise = new Promise((resolve, reject) => {
            this.http.get(`${this.baseUrl}`)
                .toPromise()
                .then(
                (data) => {
                    this.results = this.formatData(data.json());
                    resolve(this.results);
                },
                (msg) => {
                    reject(msg);

                }
                );
        });
        return promise;

    }

到目前为止,我已尝试按照官方角度测试指南编写类似的内容。在我的grid.service.spec.ts中,我有:

it('loadAcountListPromise should return Promise', () => {

            let someHttp;

            spyOn(myInnergridService, 'loadAccountListPromise').and.callThrough();

            myInnergridService.loadAccountListPromise(someHttp).then(
                ( response ) => { expect( response ).toBe( jasmine.any(Promise) );
            });
        });

这里我正在监视方法,但是通过调用.callThough()我正在使用实际的实现,从而对服务器进行真正的AJAX调用。我想避免这种情况并伪造GET请求以进行测试。我该怎么做?

1 个答案:

答案 0 :(得分:1)

首先,试验台:

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [HttpModule],
    providers: [
      YourService,
      // ... Other services
      { provide: XHRBackend, useClass: MockBackend }
    ]
  });
});

然后,在每个测试中(或在beforeEach中):

it('testing http calls ...', inject([YourService, XHRBackend], (service: YourService, http: MockBackend) => {
  let cnt: MockConnection;
  let response = { contenu: 'anything you want here' };
  http.connections.subscribe((connection: MockConnection) => {
    cnt = connection;
    // Response (CHOOSE ONE)
    connection.mockRespond(new Response(new ResponseOptions({
      body: JSON.stringify(response)
    })));
    // Error (CHOOSE ONE)
    connection.mockError(new Error('error'));
  });

  let goodCall = (method, url) => {
    expect(cnt.request.method).toBe(method);
    expect(cnt.request.url.endsWith(url)).toBe(true);
  };

  service.method().subscribe(res => goodCall(RequestMethod.Get, 'params/search'));
}));

随意询问您是否不理解!