0

I have a component that depends on a data from Route Resolve. Following is the code snippet of the router

           {
                path: 'attachment',
                component: SgCreateAttachmentComponent,
                resolve: {
                    referenceData: SgCreateAttachmentResolve
                },
                data: {
                    'seq' : 5
                },
                canActivate: [SgCreateCanActivateGaurd]
            }

Inside the component I fetch the resolve data inside ngOnInit.

ngOnInit() {

    this.standardAttachmentCategories = this._activatedRoute.snapshot.data['referenceData'].json();

   }

I am trying to unit test the ngOnInit function of the component. Following is a code snippet from my spec.

it('should ensure ngOnInit is called', () => {
    fixture.detectChanges();
});

Also, i have the following configuration of the test bed

beforeEach(async(() => {

        TestBed.configureTestingModule({
            imports: [HttpModule, SgCreateModule],
            providers: [FormBuilder, { provide: SgCreateService, useClass: SgCreateMockService },
                { provide: SgCreateAttachmentService, useClass: SgCreateAttachmentServiceMock },
                SgCreateModelService,
                { provide: Router, useClass: RouterStub },
                  { provide: ActivatedRoute, useClass: ActivatedRouteStub },
                { provide: XHRBackend, useClass: MockBackend }
            ]
        })
            .compileComponents();
        fixture = TestBed.createComponent(SgCreateAttachmentComponent);
        comp = fixture.componentInstance;



    }));

But, executing the above test throws error:

Cannot read property 'referenceData' of undefined

I have also tried the following

  it('should ensure ngOnInit is called', () => {
        const activatedRouteStub = fixture.debugElement.injector.get(ActivatedRoute);
        activatedRouteStub.testParams = { data: new Response() };
        fixture.detectChanges();
    });

But i am facing the same issue.

2
  • How does you ActivatedRouteStub look like? You have to mock the data property of it. Commented Aug 22, 2017 at 8:57
  • @lexith Thanks for pointing me to the right direction. The snapshot property of the ActivatedRouteStub was returning an object with property param. Changing param to data did the trick. Commented Aug 23, 2017 at 7:01

0

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.