Angular 单元测试为 Http Post 返回“无法读取未定义的属性”

深渊

我有一个服务,其中在构造函数中定义了我的休息点,因此我已将其设置为变量。当我运行单元测试时,这些属性返回为未定义。我对单元测试比较陌生,所以我不确定我是否错过了一个明显的步骤......

这是我的 service.ts:

import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class PulldownService {

  public pulldownData: any = [];
  public restURL;

  constructor(public http: HttpClient, public router: Router) {
    this.getEnvConf().subscribe(
        res => {
          this.restURL = res[window.location.hostname];
        }
    );
  }

  getEnvConf(): Observable<any> {
    return this.http.get('./assets/data/environment-config.json');
  }
  postClaim() {
    let headerTarget;
    if (this.restURL['target_env']) {
      headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json', 'target_env': this.restURL['targetEnv']};
    } else {
      headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json'};
    }
    const httpHeaders = new HttpHeaders(headerTarget);
    const options = { headers: httpHeaders };
    return this.http.post( this.restURL['restEndPoint'],
      { 'names' : [
        'PersonRelationType',
        'State',
        ...
        ...

      ]}, options ).subscribe(
      data => {
        // Success!
        this.pulldownData.push(data);
      }
      ,
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred.
          this.router.navigateByUrl('/error');
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          this.router.navigateByUrl('/error');
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      },
      () => {
        this.router.navigateByUrl('/getstart');
      }
    );
  }
}

这是我的 service.spec.ts

import { PulldownService } from './pulldown.service';
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpRequest } from '@angular/common/http';

describe('PulldownService', () => {
  let service: PulldownService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule, RouterTestingModule ],
      providers: [ PulldownService ]
    });
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(PulldownService);
  });
  describe('getEnvConfig', () => {
    it('should call get with the correct url', () => {
      // no subscribe method called in getEnvConfig
      // service.getEnvConf().subscribe();
      const req = httpTestingController.expectOne('./assets/data/environment-config.json');
      req.flush({ 'restEndPoint': 'http://localhost:8080/typelist?version=1', 'target_env': null});
      httpTestingController.verify();
      // expect(req.request.url.endsWith('environment-config.json')).toEqual(true);
    });
  });
  describe('postClaim', () => {

    it('should be called with proper arguments', () => {
      const responseForm = '<form />';
      const pulldownService = TestBed.get(PulldownService);
      const http = TestBed.get(HttpTestingController);
      let postResponse;

      pulldownService.postClaim().subscribe((response) => {
        postResponse = response;
      });
      http.expectOne((request: HttpRequest<any>) => {
        return request.method === 'POST'
          && request.url === 'http://localhost:8080/typelist?version=1'
          && JSON.stringify(request.body) === JSON.stringify({
            names: ['State']
          })
          && request.headers.get('Accept') === 'application/json'
          && request.headers.get('Content-Type') === 'application/json'
          && request.headers.get('target_env') === null;
      }).flush(responseForm);
      expect(postResponse).toEqual(responseForm);
    });
  });
})

我不断收到的错误是:TypeError:无法读取未定义的属性“target_env”。从我的函数中删除 'target_env' 后,我看到了一个新的、不同的 'restEndPoint' 错误。

对此的任何帮助将不胜感激。谢谢

代码安静

target_env 和 restEndPoint 的错误是因为this.restURL未定义。在您的第一个单元测试中,您已经正确地模拟了调用,但是您应该返回{ 'localhost' : { 'restEndPoint': 'http://localhost:8080/typelist?version=1', 'target_env': null } },因为在 PulldownService 的构造函数中您正在设置this.restURL = res[window.location.hostname](而不是仅仅设置this.restURL = res)。在您的第二个单元测试中,您根本没有模拟初始 get。

由于您的所有单元测试可能都需要这种处理,因此我建议将模拟调用移到beforeEach(), 之后service = TestBed.get(PulldownService);

旁注:您不需要在第二次测试中再次定义pulldownServiceand http,因为您已经有了httpTestingControllerand service

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

无法设置未定义的属性“http” - Angular 单元测试

Angular http发布错误:无法读取未定义的属性“ post”

运行npm测试(Angular 2单元测试)后无法读取未定义的属性“ subscribe”

Angular 8:ActivatedRoute 上的 Jasmine 单元测试,TypeError:无法读取未定义的属性“父”

Angular 2单元测试“无法读取未定义的属性'unsubscribe'”

Angular 4单元测试错误“ TypeError:无法读取未定义的属性'subscribe'”

单元测试 Angular 4 出现错误“TypeError:无法读取未定义的属性“订阅”

Angular 2单元测试-无法读取未定义的属性“ root”

类型错误:在单元测试 Angular 6 时无法读取未定义的属性“查询”

angular2单元测试:无法读取componentInstance.method()的属性未定义

Angular 单元测试 - TypeError:无法读取未定义的属性“名称”

无法读取未定义的属性“ post”-Angular 2

Angular 单元测试自定义验证器无法读取未定义的属性(读取“dobLengthValidator”)

(Angular http $):无法读取未定义的属性“ length”

Angular 2单元测试http.get未定义

Angular 2-无法读取未定义的属性“ get”(http未定义)

Angular2-单元测试可观察到的错误“无法读取未定义的属性'subscribe'”

TypeError:在angular2中执行单元测试时,无法读取未定义故障的属性“快照”

$ http.post给出未捕获的TypeError:无法读取angularjs中未定义的属性“ post”

Angular 2单元测试错误无法获取未定义或空引用的属性“ preventDefault”

angular2-如何在http.post单元测试中模拟错误

错误TypeError:无法读取POST HTTP调用上未定义的属性“ subscribe”-角度[8]

Angular 1.4.4(基于模块/组件的结构)-无法读取未定义的属性“ get”(http未定义)

Angular 5单元测试http响应

对具有路由器依赖项的 Angular 服务进行单元测试:“TypeError:无法读取未定义的属性‘导航’”

Angular的新HTTP客户端错误无法读取未定义的属性“数据”

使用Angular 7获取“无法读取未定义的属性'http'”

多次运行 http.get 时出错 - 无法读取未定义的属性“get” - Angular

无法在Angular中使用$ http发送POST请求-ReferenceError:未定义$ http