如何测试我是否已加载JSON-Angular2 +

时间:2018-08-23 14:29:31

标签: javascript angular typescript testing

我有一个Angular方法,该方法只是加载具有数组的本地存储的JSON文件的内容,但是我似乎无法对其进行测试。

test.ts(为简明起见简称)

describe('MyComponent', () => {

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [HttpClientTestingModule],
    });

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    component.ngOnInit();

  it('should load status data from local json', () => {
    const data = require('../../../assets/myData.json');
    component.getThings();
    expect(component.data).toEqual(data);
  });
}

MyComponent.ts

data: string[];

constructor(private httpClient: HttpClient) {}

ngOnInit() {
   this.getThings().subscribe(data =
       this.data = data;
   }
}

getData(): Observable<any> {
    const data = '../../../assets/data.json';
    return this.httpClient.get(data);
  }

1 个答案:

答案 0 :(得分:1)

在测试http请求时,您需要模拟该请求。
在下面查看有关HttpClientTestingModule的更多信息:
https://angular.io/api/common/http/testing/HttpClientTestingModule
https://medium.com/spektrakel-blog/angular-testing-snippets-httpclient-d1dc2f035eb8

下面的代码正常工作,并更新了组件代码:
组件:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-load-local-file',
  templateUrl: './load-local-file.component.html',
  styleUrls: ['./load-local-file.component.css']
})
export class LoadLocalFileComponent implements OnInit {

  data: string[];

  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
    this.getData().subscribe(data => {
      this.data = data;
    });

  }

  getData(): Observable<any> {
    const data = './data.json';
    return this.httpClient.get(data);
  }

}

规范:

  import { TestBed, async, fakeAsync, tick } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
import { LoadLocalFileComponent } from 'src/app/load-local-file/load-local-file.component';

describe('MyComponent', () => {
  let fixture, component, httpMock: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [LoadLocalFileComponent],
      imports: [HttpClientTestingModule]
    });

    fixture = TestBed.createComponent(LoadLocalFileComponent);
    component = fixture.componentInstance;
    httpMock = TestBed.get(HttpTestingController);

  }));

  it('should load status data from local json', fakeAsync(() => {
    const data = require('./data.json');

    component.ngOnInit();
    tick();
    const request = httpMock.expectOne('./data.json');
    request.flush(data);
    expect(component.data).toEqual(data);
  }));

});