TypeError:无法读取未定义的属性“管道”-角度单元测试

时间:2020-10-07 16:08:35

标签: angular unit-testing angular-unit-test

我正在尝试编写单元测试,但出现此错误。

TypeError: Cannot read property 'pipe' of undefined at Jasmine

const mockServiceObj = jasmine.createSpyObj < FormRegistrationService > (["registerForm", "pipe"]);
const getCurrentSystemPreference = jasmine.createSpyObj < CurrentSystemPreferencesService > ([
    "getCurrentSystemPreference",
    "pipe",
]);

function getServiceManagerLinks(): ServiceManagerSharedLinksComponent {
    return new ServiceManagerSharedLinksComponent(null, mockServiceObj, getCurrentSystemPreference);
}

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

针对您的情况,可能是正确的(或至少接近正确的)单元测试方法。

您具有currentSystemPreferencesService常量,并将其提供给providers。现在,在所有测试案例中都可以访问它。您还提供getPreferences字段作为可调用方法。 of(true)意味着您将返回Observable,这是pipe()的实际代码,因为您在调用.pipe(...)后立即调用了getPreferences(SystemPreference.APITestValue)

describe('ServiceManagerSharedLinksComponent ', () => {
  let component: ServiceManagerSharedLinksComponent ;
  let fixture: ComponentFixture<ServiceManagerSharedLinksComponent>;

  const currentSystemPreferencesService: any = {
    getPreferences: () => of(true),
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ServiceManagerSharedLinksComponent],
      providers: [
        {
          provide: FormRegistrationService,
          useValue: {}, // <-- You will need a different const for registerForm() method
        },
        {
          provide: CurrentSystemPreferencesService,
          useValue: currentSystemPreferencesService,
        },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(ServiceManagerSharedLinksComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it('should set display owner info when showOwnerInfo is TRUE', () => {
    expect(component.isDisplayOwnerInfoSetOnSystemPreference).toEqual(true);
  });
});