【问题标题】:TypeError: Cannot read property 'pipe' of undefined - Angular Unit testTypeError:无法读取未定义的属性“管道”-Angular 单元测试
【发布时间】:2021-01-22 15:31:03
【问题描述】:

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

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

【问题讨论】:

  • 有点不寻常的单元测试(至少对我来说)。但是,您只是在模拟方法,但什么也不返回,因此 undefined。您应该只使用 createSpy('spyName', 'getCurrentSystemPreference').and.returnValue(of({})); 返回值
  • @GytisTG 感谢您的评论,是的,这很不寻常。我刚刚在上面发布了一个屏幕截图,我收到了错误,我该如何解决?再次感谢您的帮助,Gytis。
  • 我提供了一个工作最小的例子。您可能需要更改/更新应用程序中的一些内容,因为并非所有代码部分都是可见的。但主要思想应该保持不变。

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


【解决方案1】:

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

您有currentSystemPreferencesService const 并将其提供给providers。现在它可以在所有测试用例中访问。您还提供 getPreferences 字段作为可调用方法。而of(true) 表示您返回Observable,这是pipe() 在实际代码中所需要的,因为您在调用getPreferences(SystemPreference.APITestValue) 后立即调用.pipe(...)

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

【讨论】:

    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2020-01-29
    • 1970-01-01
    • 2019-12-07
    • 2018-02-14
    • 2019-03-10
    相关资源
    最近更新 更多