0
votes

I'm getting this strange cannot read subscribe of undefined error which strangely doesn't come up somethings when it is run independently but comes up almost all the times when run without using focused testing

I have no idea as to why I'm getting this error.I tried a number of things told in various sites such as adding a afterEach loop.

Can someone please point out as to why my code is giving an error

1
Can you please share your getAccessGroup service function? - Aman Gojariya
@AmanGojariya it's mocked. problem is that it's subscribed to in the constructor. at this point in time in the tests you're still in the beforeEach, so not yet at the point where the return value of the spy is set. - Mr.Manhattan
have you tried: accessGroupSpy.getAccessGroup.and.returnValue(throwError(new Error("oops")) ? - Luxusproblem
@Luxusproblem no i havent but the same problem occurs for the test "when param has id" - coding life

1 Answers

0
votes

Your spy is called before you reach the test case:

beforeEach(() => {
    fixture = TestBed.createComponent(ViewAccessGroupComponent);  // HERE, the constructor is called
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

you could move the subscription into the ngOnInit, then the subscription will be done when fixture.detectChanges() is called, so you can move that call below setting the spy result:

  it("#getAccessGroup should show error message if API fails ", () => {

    accessGroupSpy.getAccessGroup.and.returnValue(throwError({error:{message:"error"}}))
    
    fixture.detectChanges(); // HERE instead of in beforeEach