Angular testing Cannot read property 'data' of undefinedError in Component class Component - inline template:7:24 caused by: Cannot read property 'subscribe' of undefinedAngular2 NgModel not getting value in Jasmine testHow can I test routerLinkActive in angularHow to unit test a Angular 4 component which uses router.paramMapAngular testing with keycloack “user is not logged in”error TS2707 : Generic type 'MatDialogRef<T,R>' requiers between 1 and 2 argumentsKarma error: Cannot set property 'beforePreactivation' of undefinedAngular Jasmine test not firing subscribe inside ngOnInitUnit test Angular serviceAngular Testing Modules and override

Why couldn't soldiers sight their own weapons without officers' orders?

How to display a duet in lyrics?

How do I calculate the difference in lens reach between a superzoom compact and a DSLR zoom lens?

Physics of Guitar frets and sound

How does The Fools Guild make its money?

How do I explain to a team that the project they will work on for six months will 100% fail?

Word or idiom defining something barely functional

What are good ways to improve as a writer other than writing courses?

Is it true that control+alt+delete only became a thing because IBM would not build Bill Gates a computer with a task manager button?

How would I as a DM create a smart phone-like spell/device my players could use?

Tikzcd pullback square issue

What is the best way to cause swarm intelligence to be destroyed?

Does docker consume CPU the way VMs do?

Why is there a need to prevent a racist, sexist, or otherwise bigoted vendor from discriminating who they sell to?

Can I call myself an assistant professor without a PhD

Does a code snippet compile? Or does it gets compiled?

Is there a loss of quality when converting RGB to HEX?

Is this cheap "air conditioner" able to cool a room?

Pandas: fill one column with count of # of obs between occurrences in a 2nd column

When "he's gone" means "he's dead", is it a contraction of "he is" or "he has"?

Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?

Improving software when the author can see no need for improvement

How to help new students accept function notation

Is there a way to create a report for the failed entries while calling REST API



Angular testing Cannot read property 'data' of undefined


Error in Component class Component - inline template:7:24 caused by: Cannot read property 'subscribe' of undefinedAngular2 NgModel not getting value in Jasmine testHow can I test routerLinkActive in angularHow to unit test a Angular 4 component which uses router.paramMapAngular testing with keycloack “user is not logged in”error TS2707 : Generic type 'MatDialogRef<T,R>' requiers between 1 and 2 argumentsKarma error: Cannot set property 'beforePreactivation' of undefinedAngular Jasmine test not firing subscribe inside ngOnInitUnit test Angular serviceAngular Testing Modules and override






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.



Here My code for the component



 export class GridRendererComponent implements ICellRendererAngularComp 
public params: any;
// Icons
faEdit = faEdit;
faTrashAlt = faTrashAlt;

constructor(private router: Router, public dialog: MatDialog)

agInit(params: any): void
this.params = params;

deleteDomain()
this.dialog.open(ConfirmDialogComponent,
panelClass: '_small-dialog',
disableClose: true,
position: top: '50px' ,
data:
title: 'Delete Domain',
description: `Are you sure do you want to delete domain Contract ID: $
this.params.data.contactId
?`

);




Here is the below code for a spec which I tried



 import async, ComponentFixture, TestBed from '@angular/core/testing';

import GridRendererComponent from './grid-renderer.component';
import RouterTestingModule from '@angular/router/testing';
import FeaturesModule from '../../features.module';
import Routes, Router from '@angular/router';
import BrowserAnimationsModule from '@angular/platform-browser/animations';
import MatDialog, MatDialogRef, MAT_DIALOG_DATA from '@angular/material';
import NAccessRequestComponent from '../../n-access-request/n-access-request.component';

const routes: Routes = [
path: 'n-access-request', component: NAccessRequestComponent ,
];

describe('GridRendererComponent', () =>
let gridRendererComponent: GridRendererComponent;
let dialog : MatDialog;
let router: Router;

beforeEach(() =>
TestBed.configureTestingModule(
imports: [
RouterTestingModule.withRoutes(routes),
FeaturesModule,
BrowserAnimationsModule
],
declarations: [ ]
)

.compileComponents();
router = TestBed.get(Router);
router.initialNavigation();
);

beforeEach(() =>
const fixture = TestBed.createComponent(GridRendererComponent);
gridRendererComponent = fixture.componentInstance;
fixture.detectChanges();
);

it('should create', () =>
expect(gridRendererComponent).toBeTruthy();
);

it('agInit', () =>
let params =
"column" : "status"
;
gridRendererComponent.agInit(params);
expect(gridRendererComponent.params).not.toBe(null);
);


it('approveRequest', () =>
let params =
"data" :
"contactId" : '5',

;
spyOn(gridRendererComponent.dialog, 'open').and.returnValue(true);
gridRendererComponent.deleteDomain();
expect(gridRendererComponent.dialog.open).toHaveBeenCalled();
expect(gridRendererComponent.params.data.contactId).not.toBe(null);
);

);









share|improve this question


























  • You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

    – JB Nizet
    Mar 27 at 7:25

















0















I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.



Here My code for the component



 export class GridRendererComponent implements ICellRendererAngularComp 
public params: any;
// Icons
faEdit = faEdit;
faTrashAlt = faTrashAlt;

constructor(private router: Router, public dialog: MatDialog)

agInit(params: any): void
this.params = params;

deleteDomain()
this.dialog.open(ConfirmDialogComponent,
panelClass: '_small-dialog',
disableClose: true,
position: top: '50px' ,
data:
title: 'Delete Domain',
description: `Are you sure do you want to delete domain Contract ID: $
this.params.data.contactId
?`

);




Here is the below code for a spec which I tried



 import async, ComponentFixture, TestBed from '@angular/core/testing';

import GridRendererComponent from './grid-renderer.component';
import RouterTestingModule from '@angular/router/testing';
import FeaturesModule from '../../features.module';
import Routes, Router from '@angular/router';
import BrowserAnimationsModule from '@angular/platform-browser/animations';
import MatDialog, MatDialogRef, MAT_DIALOG_DATA from '@angular/material';
import NAccessRequestComponent from '../../n-access-request/n-access-request.component';

const routes: Routes = [
path: 'n-access-request', component: NAccessRequestComponent ,
];

describe('GridRendererComponent', () =>
let gridRendererComponent: GridRendererComponent;
let dialog : MatDialog;
let router: Router;

beforeEach(() =>
TestBed.configureTestingModule(
imports: [
RouterTestingModule.withRoutes(routes),
FeaturesModule,
BrowserAnimationsModule
],
declarations: [ ]
)

.compileComponents();
router = TestBed.get(Router);
router.initialNavigation();
);

beforeEach(() =>
const fixture = TestBed.createComponent(GridRendererComponent);
gridRendererComponent = fixture.componentInstance;
fixture.detectChanges();
);

it('should create', () =>
expect(gridRendererComponent).toBeTruthy();
);

it('agInit', () =>
let params =
"column" : "status"
;
gridRendererComponent.agInit(params);
expect(gridRendererComponent.params).not.toBe(null);
);


it('approveRequest', () =>
let params =
"data" :
"contactId" : '5',

;
spyOn(gridRendererComponent.dialog, 'open').and.returnValue(true);
gridRendererComponent.deleteDomain();
expect(gridRendererComponent.dialog.open).toHaveBeenCalled();
expect(gridRendererComponent.params.data.contactId).not.toBe(null);
);

);









share|improve this question


























  • You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

    – JB Nizet
    Mar 27 at 7:25













0












0








0








I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.



Here My code for the component



 export class GridRendererComponent implements ICellRendererAngularComp 
public params: any;
// Icons
faEdit = faEdit;
faTrashAlt = faTrashAlt;

constructor(private router: Router, public dialog: MatDialog)

agInit(params: any): void
this.params = params;

deleteDomain()
this.dialog.open(ConfirmDialogComponent,
panelClass: '_small-dialog',
disableClose: true,
position: top: '50px' ,
data:
title: 'Delete Domain',
description: `Are you sure do you want to delete domain Contract ID: $
this.params.data.contactId
?`

);




Here is the below code for a spec which I tried



 import async, ComponentFixture, TestBed from '@angular/core/testing';

import GridRendererComponent from './grid-renderer.component';
import RouterTestingModule from '@angular/router/testing';
import FeaturesModule from '../../features.module';
import Routes, Router from '@angular/router';
import BrowserAnimationsModule from '@angular/platform-browser/animations';
import MatDialog, MatDialogRef, MAT_DIALOG_DATA from '@angular/material';
import NAccessRequestComponent from '../../n-access-request/n-access-request.component';

const routes: Routes = [
path: 'n-access-request', component: NAccessRequestComponent ,
];

describe('GridRendererComponent', () =>
let gridRendererComponent: GridRendererComponent;
let dialog : MatDialog;
let router: Router;

beforeEach(() =>
TestBed.configureTestingModule(
imports: [
RouterTestingModule.withRoutes(routes),
FeaturesModule,
BrowserAnimationsModule
],
declarations: [ ]
)

.compileComponents();
router = TestBed.get(Router);
router.initialNavigation();
);

beforeEach(() =>
const fixture = TestBed.createComponent(GridRendererComponent);
gridRendererComponent = fixture.componentInstance;
fixture.detectChanges();
);

it('should create', () =>
expect(gridRendererComponent).toBeTruthy();
);

it('agInit', () =>
let params =
"column" : "status"
;
gridRendererComponent.agInit(params);
expect(gridRendererComponent.params).not.toBe(null);
);


it('approveRequest', () =>
let params =
"data" :
"contactId" : '5',

;
spyOn(gridRendererComponent.dialog, 'open').and.returnValue(true);
gridRendererComponent.deleteDomain();
expect(gridRendererComponent.dialog.open).toHaveBeenCalled();
expect(gridRendererComponent.params.data.contactId).not.toBe(null);
);

);









share|improve this question
















I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.I am trying to write a test case for the component but I am getting the error as Cannot read property 'data' of undefined. I am using angular 6. Please look at deleteDomain() method.



Here My code for the component



 export class GridRendererComponent implements ICellRendererAngularComp 
public params: any;
// Icons
faEdit = faEdit;
faTrashAlt = faTrashAlt;

constructor(private router: Router, public dialog: MatDialog)

agInit(params: any): void
this.params = params;

deleteDomain()
this.dialog.open(ConfirmDialogComponent,
panelClass: '_small-dialog',
disableClose: true,
position: top: '50px' ,
data:
title: 'Delete Domain',
description: `Are you sure do you want to delete domain Contract ID: $
this.params.data.contactId
?`

);




Here is the below code for a spec which I tried



 import async, ComponentFixture, TestBed from '@angular/core/testing';

import GridRendererComponent from './grid-renderer.component';
import RouterTestingModule from '@angular/router/testing';
import FeaturesModule from '../../features.module';
import Routes, Router from '@angular/router';
import BrowserAnimationsModule from '@angular/platform-browser/animations';
import MatDialog, MatDialogRef, MAT_DIALOG_DATA from '@angular/material';
import NAccessRequestComponent from '../../n-access-request/n-access-request.component';

const routes: Routes = [
path: 'n-access-request', component: NAccessRequestComponent ,
];

describe('GridRendererComponent', () =>
let gridRendererComponent: GridRendererComponent;
let dialog : MatDialog;
let router: Router;

beforeEach(() =>
TestBed.configureTestingModule(
imports: [
RouterTestingModule.withRoutes(routes),
FeaturesModule,
BrowserAnimationsModule
],
declarations: [ ]
)

.compileComponents();
router = TestBed.get(Router);
router.initialNavigation();
);

beforeEach(() =>
const fixture = TestBed.createComponent(GridRendererComponent);
gridRendererComponent = fixture.componentInstance;
fixture.detectChanges();
);

it('should create', () =>
expect(gridRendererComponent).toBeTruthy();
);

it('agInit', () =>
let params =
"column" : "status"
;
gridRendererComponent.agInit(params);
expect(gridRendererComponent.params).not.toBe(null);
);


it('approveRequest', () =>
let params =
"data" :
"contactId" : '5',

;
spyOn(gridRendererComponent.dialog, 'open').and.returnValue(true);
gridRendererComponent.deleteDomain();
expect(gridRendererComponent.dialog.open).toHaveBeenCalled();
expect(gridRendererComponent.params.data.contactId).not.toBe(null);
);

);






angular unit-testing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 4 at 21:18









neo

3781 silver badge10 bronze badges




3781 silver badge10 bronze badges










asked Mar 27 at 6:50









Ramesh vemulaRamesh vemula

134 bronze badges




134 bronze badges















  • You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

    – JB Nizet
    Mar 27 at 7:25

















  • You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

    – JB Nizet
    Mar 27 at 7:25
















You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

– JB Nizet
Mar 27 at 7:25





You haven't posted the stack trace, so I guess that this happens at the line this.params.data.contactId. The error tells you that it can't read propery data of undefined, which means that this.params is undefined, which means you haven't initialized your component as it should be for this code to work.

– JB Nizet
Mar 27 at 7:25












1 Answer
1






active

oldest

votes


















0














I have found few mistakes you have made, again question itself has lack of information.



First: Define your components inside the declaration closure. I've found you have 2 components to be added, GridRendererComponent and ConfirmDialogComponent.



You don't need to initiate router navigation at very first.



// router = TestBed.get(Router);
// router.initialNavigation();


Change your spyOn method to following,



spyOn(gridRendererComponent.dialog, 'open');


Since you are spying on the method it'll never call, so you don't need to define data object here.
Hence remove last assertion as well.



// expect(gridRendererComponent.params.data.contactId).not.toBe(null);





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371348%2fangular-testing-cannot-read-property-data-of-undefined%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I have found few mistakes you have made, again question itself has lack of information.



    First: Define your components inside the declaration closure. I've found you have 2 components to be added, GridRendererComponent and ConfirmDialogComponent.



    You don't need to initiate router navigation at very first.



    // router = TestBed.get(Router);
    // router.initialNavigation();


    Change your spyOn method to following,



    spyOn(gridRendererComponent.dialog, 'open');


    Since you are spying on the method it'll never call, so you don't need to define data object here.
    Hence remove last assertion as well.



    // expect(gridRendererComponent.params.data.contactId).not.toBe(null);





    share|improve this answer





























      0














      I have found few mistakes you have made, again question itself has lack of information.



      First: Define your components inside the declaration closure. I've found you have 2 components to be added, GridRendererComponent and ConfirmDialogComponent.



      You don't need to initiate router navigation at very first.



      // router = TestBed.get(Router);
      // router.initialNavigation();


      Change your spyOn method to following,



      spyOn(gridRendererComponent.dialog, 'open');


      Since you are spying on the method it'll never call, so you don't need to define data object here.
      Hence remove last assertion as well.



      // expect(gridRendererComponent.params.data.contactId).not.toBe(null);





      share|improve this answer



























        0












        0








        0







        I have found few mistakes you have made, again question itself has lack of information.



        First: Define your components inside the declaration closure. I've found you have 2 components to be added, GridRendererComponent and ConfirmDialogComponent.



        You don't need to initiate router navigation at very first.



        // router = TestBed.get(Router);
        // router.initialNavigation();


        Change your spyOn method to following,



        spyOn(gridRendererComponent.dialog, 'open');


        Since you are spying on the method it'll never call, so you don't need to define data object here.
        Hence remove last assertion as well.



        // expect(gridRendererComponent.params.data.contactId).not.toBe(null);





        share|improve this answer













        I have found few mistakes you have made, again question itself has lack of information.



        First: Define your components inside the declaration closure. I've found you have 2 components to be added, GridRendererComponent and ConfirmDialogComponent.



        You don't need to initiate router navigation at very first.



        // router = TestBed.get(Router);
        // router.initialNavigation();


        Change your spyOn method to following,



        spyOn(gridRendererComponent.dialog, 'open');


        Since you are spying on the method it'll never call, so you don't need to define data object here.
        Hence remove last assertion as well.



        // expect(gridRendererComponent.params.data.contactId).not.toBe(null);






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 27 at 9:42









        neoneo

        3781 silver badge10 bronze badges




        3781 silver badge10 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371348%2fangular-testing-cannot-read-property-data-of-undefined%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript