首页 > 解决方案 > TypeError:无法读取未定义的属性“管道”-Angular 单元测试

问题描述

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

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);
}

在此处输入图像描述

在此处输入图像描述

标签: angularunit-testingangular-unit-test

解决方案


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

您有currentSystemPreferencesServiceconst 并将其提供给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);
  });
});

推荐阅读