读取JSON文件的测试服务

时间:2019-03-14 02:30:47

标签: angular unit-testing

我有以下服务,可从json文件中提取数据:

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

@Injectable()
export class DataService {
  public timezones: any;
  private timeZonesDataPath = './assets/data/timezones.json';

  constructor(
    public httpClient: HttpClient
  ) {
    this.timezones = this.httpClient.get(this.timeZonesDataPath);
  }

  public getAllTimezones(): Observable<any> {
    return this.timezones;
  }
}

我已经开始对其进行测试,但是一直遇到问题。在线上的大多数文档都是用于测试真实的api的,我只想检查一下我的json文件是否正确加载,有什么办法可以做到这一点。到目前为止,这是我的测试脚本。

import { TestBed, inject } from '@angular/core/testing';
import { DataService } from './data.service';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('DataService unit tests', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [
      RouterTestingModule,
      HttpClientTestingModule
    ],
    providers: [
      DataService
    ]
  }));

  describe('getAllTimezones()', () => {
    it('should return total number of timezones', () => {
      const dataService = TestBed.get(DataService);
      const httpMock = TestBed.get(HttpTestingController);
      dataService.getAllTimezones().subscribe((data: any) => {
        console.log(data);
        expect(data.length).toBeGreaterThan(0);
      });

      const req = httpMock.expectOne('./assets/data/timezones.json');
      console.log(req);
      expect(req.request.method).toEqual('GET');
      req.flush({data: 'test'});
    });
  });

我目前收到错误消息:DataService unit tests getAllTimezones() should return total number of timezones FAILED Expected undefined to be greater than 0.-如何解决?我希望只看到以下内容:

[
  {
    "value": "Dateline Standard Time",
    "abbr": "DST",
    "offset": -12,
    "isdst": false,
    "text": "(UTC-12:00) International Date Line West",
    "utc": [
      "Etc/GMT+12"
    ]
  },
  {
    "value": "UTC-11",
    "abbr": "U",
    "offset": -11,
    "isdst": false,
    "text": "(UTC-11:00) Coordinated Universal Time-11",
    "utc": [
      "Etc/GMT+11",
      "Pacific/Midway",
      "Pacific/Niue",
      "Pacific/Pago_Pago"
    ]
  }
]

0 个答案:

没有答案