angular 6 unit testing - how can I inject a class with static property for testing
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
add a comment |
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
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
add a comment |
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
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
angular unit-testing
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
add a comment |
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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