簡體   English   中英

Jasmine 單元測試 - 類型錯誤:無法讀取未定義的屬性(讀取“管道”)

[英]Jasmine unit tests - TypeError: Cannot read properties of undefined (reading 'pipe')

TypeError: Cannot read properties of undefined (reading 'pipe') at MyComponent.fetchData

Angular中運行我的Jasmine單元測試時出現上述錯誤。 現有的beforeEach不喜歡我在my.component.tsngOnInit()中的新fetchData function。 我在本規范中的所有六個測試都因相同的錯誤而失敗。 有任何想法嗎?

我的.component.ts

export class MyComponent extends BaseComponent implements OnInit {

  constructor(
    private myService: MyService,
  ) {}

  ngOnInit(): void {

    this.fetchData();

  }

  public fetchData() {
        this.myService.getData()
        .pipe(takeUntil(this.unsubscribe$)).subscribe(  //this.unsubscribe$ gets destroyed in BaseComponent's ngOnDestroy(). Only purpose of BaseComponent is to unsubscribe from observables
          data => {
            if (data) {
              return this.myService.getTypesByCategory(data);
            }
          }
        );
    return;
  }

我的.service.ts

export class MyService {

  getData(): Observable<any> {
    return this.httpClient.get('https://myurl.com/myquerystring')
    .pipe(this.showError());
  }

  getTypesByCategory(data) {
                
    for (let region of data.regions) {
          return this.selectType(myArg);
    }
  }

  selectType(myArg): void {
       // do stuff
    
  }
  
}

我的.component.spec.ts

import { ComponentFixture, TestBed, fakeAsync, tick, waitForAsync } from '@angular/core/testing';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { Router } from '@angular/router';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { MyService } from 'src/app/my.service';
import { MyComponent } from './mycomponent';

describe('DeviceRegistrationComponent', () => {
  let component: DeviceRegistrationComponent;
  let fixture: ComponentFixture<DeviceRegistrationComponent>;
  let routerSpy: jasmine.SpyObj<Router>;
  let myServiceSpy: jasmine.SpyObj<MyService>;

  beforeEach(
    waitForAsync(() => {
      const myServiceObj = jasmine.createSpyObj('myService', [
        'selectType',
        'getData',
      ]);

      TestBed.configureTestingModule({
        imports: [
          HttpClientTestingModule,
          RouterTestingModule,
          ReactiveFormsModule,
        ],
        declarations: [MyComponent],
        providers: [
          FormBuilder,
          { provide: MyService, useValue: myServiceObj },
        ],
        schemas: [NO_ERRORS_SCHEMA],
      }).compileComponents();


      routerSpy = TestBed.inject(Router) as jasmine.SpyObj<Router>;
      myServiceSpy = TestBed.inject(MyService) as jasmine.SpyObj<MyService>;
      
    }),
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

    expect(myServiceSpy.selectType).toHaveBeenCalledWith(true);
  });

  // 5 more tests all fail with the same error

});

您的組件期望getData()返回一個可觀察對象,然后將.pipe(...)添加到該對象。 默認情況下,間諜 object 方法返回undefined 您需要模擬函數以返回值

const myServiceObj = jasmine.createSpyObj('myService', [
        'selectType',
        'getData',
      ]);

您也可以模擬返回值

myServiceObj.getData
  .and
  .returnValue(of(true));

暫無
暫無

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

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