簡體   English   中英

Jasmine/Angular:無法讀取未定義的屬性“patchValue”(組件測試)

[英]Jasmine/Angular: Cannot read property 'patchValue' of undefined (component testing)

在我的單元測試中,我正在測試是否正在調用我的服務。 我有一個名為 loadUser() 的函數。 此函數使用服務 getData,從 url 檢索所有用戶。 然后,它將用戶 ID 和該特定用戶的信息(姓名、姓氏等)加載到表單中。 從這里,用戶可以編輯他們的憑據。 此函數使用 patchValue 將數據顯示到正確的表單字段。 現在我只是想測試我的服務 getData 是否被調用,就是這樣。 運行我的測試時,我收到此錯誤: TypeError: Cannot read property 'patchValue' of undefined 我希望我的測試表明 getData 已被調用。 這是我的測試,下面是我的功能(為簡潔起見,我只發布了必要的代碼)。 我發布了我的設置是因為我在那里遺漏了什么?

規格:

    fdescribe('User Component', () => {
    let httpService: HttpService;
    let userComponent: UserComponent
    let fixture: ComponentFixture<UserComponent>
    let debugElement: DebugElement;

beforeEach(async() => {
    TestBed.configureTestingModule({
      declarations: [
        UserComponent, 
      ],
      imports: [HttpModule, FormsModule,ReactiveFormsModule],
      providers: [
          HttpService
      ],
  }).compileComponents();
});

beforeEach(() => {
     fixture = TestBed.createComponent(UserComponent);
     userComponent = fixture.componentInstance;
     debugElement = fixture.debugElement;
     httpService = debugElement.injector.get(HttpService);

fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {
    let url = AppConfig.URL_UserById'

    let getDataSpy= spyOn(httpService,'getData').and.returnValue(Observable.of(url));
        userComponent.loadUser();
     expect(getDataSpy).toHaveBeenCalled();
   })))
})

成分:

  loadUser() {
this.httpService.getData(AppConfig.URL_UserById + "?UserID=" + this.userId)
  .catch((error: Response | any) => {
    this.showAlertWindow(this.exceptionMessage);
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  })
  .subscribe((res: any) => {
    this.frmUser.patchValue({

      FirstName: res.FirstName,
      MiddleName: res.MiddleName,
      EmailAddress: res.EmailAddress,
      LastName: res.LastName

    });
    this.setUserAccess(res.UserAccessDetail)

  });

現在,如果我注釋掉this.frmUser.patchValue){FirstName...} ,則測試通過並成功檢查 getData() 是否被調用。 所以我猜我需要啟動 patchValue 或類似的東西。 謝謝你。

問題的簡單解決方法。 在我的 ngOnInit 組件中,我創建了我的用戶表單。 我需要做的就是做userComponent.ngOnInit()並且測試通過了。

工作測試的完整代碼:

fit('should have getUsers() call the service GetData()', inject([HttpService], fakeAsync((httpService) => {

    let url = AppConfig.URL_UserById + "?UserID=" + this.userId

    let getDataSpy= spyOn(httpService, 'getData').and.returnValue(Observable.of(url));

   userComponent.ngOnInit();
   userComponent.loadUser();

        expect(getDataSpy).toHaveBeenCalled();

   })))
})

只需將其添加到我的

 ngOnInit(): void {
   this.myForm.patchValue({
      username: this.AUTH_USER.username
    })
}

解決了這個問題:請記住,我已經使用登錄用戶的初始值聲明了 AUTH_USER。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM