angular 6 unit testing - how can I inject a class with static property for testing












1















I have a class AppGlobal which get injected in the AppModule and then I am using this singleton class for creating dependencies instances.
but I am getting the following error :




TypeError: Cannot read property 'get' of undefined
at new StopWatchComponent (webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)




 @Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
public static injector: Injector;
constructor(injector: Injector) {
AppGlobal.injector = injector;
}
}


component to be tested



export class StopWatchComponent  implements OnInit {
public title: string;
private stopWatchService: StopWatchService;
constructor() {
this.stopWatchService = AppGlobal.injector.get(StopWatchService);
console.log('constructor');
}


root module



export class AppModule {
constructor(_appGlobal: AppGlobal) {
}
}


test cases



describe('StopWatchComponent', () => {
let component: StopWatchComponent;
let fixture: ComponentFixture<StopWatchComponent>;
// let el: HTMLElement;

beforeEach(async(() => {

TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [ StopWatchComponent ],
providers: [AppGlobal
{provide: StopWatchService, useClass: StopWatchServiceMock}]
}).compileComponents()
.then(() => {
console.log('configureTestingModule ok');

}).catch((e) => {
console.log(e.message);
throw e;
});

fixture = TestBed.createComponent(StopWatchComponent);
component = fixture.componentInstance;
fixture.detectChanges();

}));

it('should have title User stopwatch', () => {
expect(component.title).toEqual('User stopwatch');
});









share|improve this question




















  • 2





    Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

    – JB Nizet
    Nov 25 '18 at 23:37











  • @jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

    – Mak Dublin
    Nov 26 '18 at 20:58


















1















I have a class AppGlobal which get injected in the AppModule and then I am using this singleton class for creating dependencies instances.
but I am getting the following error :




TypeError: Cannot read property 'get' of undefined
at new StopWatchComponent (webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)




 @Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
public static injector: Injector;
constructor(injector: Injector) {
AppGlobal.injector = injector;
}
}


component to be tested



export class StopWatchComponent  implements OnInit {
public title: string;
private stopWatchService: StopWatchService;
constructor() {
this.stopWatchService = AppGlobal.injector.get(StopWatchService);
console.log('constructor');
}


root module



export class AppModule {
constructor(_appGlobal: AppGlobal) {
}
}


test cases



describe('StopWatchComponent', () => {
let component: StopWatchComponent;
let fixture: ComponentFixture<StopWatchComponent>;
// let el: HTMLElement;

beforeEach(async(() => {

TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [ StopWatchComponent ],
providers: [AppGlobal
{provide: StopWatchService, useClass: StopWatchServiceMock}]
}).compileComponents()
.then(() => {
console.log('configureTestingModule ok');

}).catch((e) => {
console.log(e.message);
throw e;
});

fixture = TestBed.createComponent(StopWatchComponent);
component = fixture.componentInstance;
fixture.detectChanges();

}));

it('should have title User stopwatch', () => {
expect(component.title).toEqual('User stopwatch');
});









share|improve this question




















  • 2





    Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

    – JB Nizet
    Nov 25 '18 at 23:37











  • @jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

    – Mak Dublin
    Nov 26 '18 at 20:58
















1












1








1








I have a class AppGlobal which get injected in the AppModule and then I am using this singleton class for creating dependencies instances.
but I am getting the following error :




TypeError: Cannot read property 'get' of undefined
at new StopWatchComponent (webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)




 @Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
public static injector: Injector;
constructor(injector: Injector) {
AppGlobal.injector = injector;
}
}


component to be tested



export class StopWatchComponent  implements OnInit {
public title: string;
private stopWatchService: StopWatchService;
constructor() {
this.stopWatchService = AppGlobal.injector.get(StopWatchService);
console.log('constructor');
}


root module



export class AppModule {
constructor(_appGlobal: AppGlobal) {
}
}


test cases



describe('StopWatchComponent', () => {
let component: StopWatchComponent;
let fixture: ComponentFixture<StopWatchComponent>;
// let el: HTMLElement;

beforeEach(async(() => {

TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [ StopWatchComponent ],
providers: [AppGlobal
{provide: StopWatchService, useClass: StopWatchServiceMock}]
}).compileComponents()
.then(() => {
console.log('configureTestingModule ok');

}).catch((e) => {
console.log(e.message);
throw e;
});

fixture = TestBed.createComponent(StopWatchComponent);
component = fixture.componentInstance;
fixture.detectChanges();

}));

it('should have title User stopwatch', () => {
expect(component.title).toEqual('User stopwatch');
});









share|improve this question
















I have a class AppGlobal which get injected in the AppModule and then I am using this singleton class for creating dependencies instances.
but I am getting the following error :




TypeError: Cannot read property 'get' of undefined
at new StopWatchComponent (webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)




 @Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
public static injector: Injector;
constructor(injector: Injector) {
AppGlobal.injector = injector;
}
}


component to be tested



export class StopWatchComponent  implements OnInit {
public title: string;
private stopWatchService: StopWatchService;
constructor() {
this.stopWatchService = AppGlobal.injector.get(StopWatchService);
console.log('constructor');
}


root module



export class AppModule {
constructor(_appGlobal: AppGlobal) {
}
}


test cases



describe('StopWatchComponent', () => {
let component: StopWatchComponent;
let fixture: ComponentFixture<StopWatchComponent>;
// let el: HTMLElement;

beforeEach(async(() => {

TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule
],
declarations: [ StopWatchComponent ],
providers: [AppGlobal
{provide: StopWatchService, useClass: StopWatchServiceMock}]
}).compileComponents()
.then(() => {
console.log('configureTestingModule ok');

}).catch((e) => {
console.log(e.message);
throw e;
});

fixture = TestBed.createComponent(StopWatchComponent);
component = fixture.componentInstance;
fixture.detectChanges();

}));

it('should have title User stopwatch', () => {
expect(component.title).toEqual('User stopwatch');
});






angular unit-testing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 26 '18 at 13:44









Milad Bahmanabadi

821717




821717










asked Nov 25 '18 at 23:31









Mak DublinMak Dublin

63




63








  • 2





    Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

    – JB Nizet
    Nov 25 '18 at 23:37











  • @jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

    – Mak Dublin
    Nov 26 '18 at 20:58
















  • 2





    Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

    – JB Nizet
    Nov 25 '18 at 23:37











  • @jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

    – Mak Dublin
    Nov 26 '18 at 20:58










2




2





Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

– JB Nizet
Nov 25 '18 at 23:37





Angular comes witha DI system, whose main objective is to make things testable. You transformed it back into a global static factory when components lookup their dependencies instead of using DI. And now you find out that it makes testing difficult. The est advice is: drop that AppGlobal, and use DI as it's supposed to be used.

– JB Nizet
Nov 25 '18 at 23:37













@jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

– Mak Dublin
Nov 26 '18 at 20:58







@jb Nizet : I agree with you. this is just r&d i was doing to make the code generic. in actual code, I have a base component and all the logic of the injection goes there so that I don't have to inject any dependency from derived components i.e. activedroute, logservice, toster, utityservice etc. I will try some other design to make it testable. thanks for you comment

– Mak Dublin
Nov 26 '18 at 20:58














0






active

oldest

votes











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%2f53473058%2fangular-6-unit-testing-how-can-i-inject-a-class-with-static-property-for-testi%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















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%2f53473058%2fangular-6-unit-testing-how-can-i-inject-a-class-with-static-property-for-testi%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

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks