2

I'm trying to write a unit test and I'm getting this error.

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

Jacob
  • 59
  • 7
  • A bit unusual unit test (at least for me). However, you're just mocking methods but returning nothing, thus `undefined`. You should return value with just `createSpy('spyName', 'getCurrentSystemPreference').and.returnValue(of({}));` – Gynteniuxas Oct 07 '20 at 17:35
  • @GytisTG Thank you for the comment, yes it's quite unusual. I just posted a screenshot above, with the error that I received, how would I fix that? Thank you again for your help, Gytis. – Jacob Oct 07 '20 at 17:43
  • I have provided a working minimal example. You may need to change/update a few things in your app since not all code parts are visible. But the main idea should remain the same. – Gynteniuxas Oct 07 '20 at 18:19

1 Answers1

1

Probably the correct (or at least close to correct) unit tests approach for your situation.

You have currentSystemPreferencesService const and provide it to providers. Now it's accessible in all tests cases. You also provide getPreferences field as callable method. And of(true) means you return on Observable which is needed for pipe() in real code since you immediately call .pipe(...) after calling 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);
  });
});
Gynteniuxas
  • 7,035
  • 18
  • 38
  • 54