【问题标题】:Angular unit testing of service using HttpClientTestingModule and HttpTestingController使用 HttpClientTestingModule 和 HttpTestingController 对服务进行角度单元测试
【发布时间】:2021-12-01 02:36:00
【问题描述】:

我在测试我的应用程序时遇到问题。主要是我的问题是 URL。这是我的测试床:

  let service: AdnimistrationSiteService;
  let httpClient: HttpClient
  let httpClientMock: HttpTestingController;
  let helper : Helper;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [AdnimistrationSiteService]
    });
    httpClient = getTestBed().inject(HttpClient);
    service = getTestBed().inject(AdnimistrationSiteService);
    httpClientMock = getTestBed().inject(HttpTestingController)
    helper = new Helper();
  });

  afterEach(() => {
    httpClientMock.verify();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

我要测试的调用如下所示:

 getAllFilesWithIcons(id_name: string): Observable<any[]> {
    let parameters = new HttpParams().set("id_name", id_name);
    let url = environment.baseUrl + "/api/v1/example/get_example_api";
    return this.http.get(url, {params: parameters})
    .pipe(
      map(products => products["result"]),
      catchError(err => {
        console.log(err);
        return throwError(err)
      })
    )
  }

我真的不明白我必须在这里测试什么。是对服务器进行真实调用还是模拟调用。如果是这样,我不知道参数。试了很多次,每次都报错。

我的测试如下所示:

    it("Should return data", () => {
        const testData = [
          {'element_filename': 'something', 'icon_symbol': 'symbol_test', "inventory_id": "inv " , "sensors": ["abc " , "eff "]}
        ]
        service.getAllFilesWithIcons("id_name").subscribe((id) => {
          console.log(id)
          console.log(testData)
          expect(testData).toBe(id, "should mocked data")
        })
        const req = httpClientMock.expectOne(environment.baseUrl + "/api/v1/example/get_example_api" + '?id_name=id_name')

        // expect(req.cancelled).toBeFalsy()
        expect(req.request.method).toBe("GET")
        req.flush(testData)
    })

但在这种情况下,“id”始终未定义。

【问题讨论】:

    标签: angular jasmine karma-jasmine angular-test angular-testing-library


    【解决方案1】:

    id 未定义,因为您正在映射到 product['result'] 并且 result 在对象上不存在。

    要修复它,试试这个:

    it("Should return data", () => {
            // !! change this line to have result key !!
            const testData = { result: [
              {'element_filename': 'something', 'icon_symbol': 'symbol_test', "inventory_id": "inv " , "sensors": ["abc " , "eff "]}
            ] };
            service.getAllFilesWithIcons("id_name").subscribe((id) => {
              // id should not be undefined anymore
              console.log(id)
              expect(id).toBeTruthy();
              console.log(testData)
            })
            const req = httpClientMock.expectOne(environment.baseUrl + "/api/v1/example/get_example_api" + '?id_name=id_name')
    
            // expect(req.cancelled).toBeFalsy()
            expect(req.request.method).toBe("GET")
            req.flush(testData)
        })
    

    【讨论】:

    • 感谢它对我帮助很大
    猜你喜欢
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多