0

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

4
  • Can you please share your getAccessGroup service function? Commented Mar 4, 2021 at 12:26
  • @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. Commented Mar 4, 2021 at 12:30
  • have you tried: accessGroupSpy.getAccessGroup.and.returnValue(throwError(new Error("oops")) ? Commented Mar 4, 2021 at 12:31
  • @Luxusproblem no i havent but the same problem occurs for the test "when param has id" Commented Mar 4, 2021 at 12:35

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Would moving the subscription inside ngOnInit lifecycle affect the whole application in any way ??
no, because that's always the first thing that is called on the component. in generall, subscriptions should always be done in ngOnInit...that's basically what it's for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.