Reputation: 3566
I'm trying to create an instance of a component in component's testing file. But when I do something like this:
let componentInstance = new component();
it hits the component constructor, which further has something in its body,
constructor( param ) {
......;
......;
}
now the constructor body uses some other service, therefore whenever I'm trying to create an instance of this component and run it, it complains about the unknown properties which are being used in the constructor body (because the spec file obviously doesn't know about what is happening in the constructor body of our component.
Any ideas how can I create an instance of that component in its spec file?
Upvotes: 0
Views: 2168
Reputation: 208984
You should configure a testing module before each test, using the TestBed
. Here you can declare you component to test, and any providers it needs. Then you create the component using the TestBed
also.
beforeEach(() => {
TestBed.configureTestingModule({
imports: []
declarations: [ TestComponent ],
providers: [ TestService ]
});
});
it('...', () => {
let fixture = TestBed.createComponnt(TestComponent);
let component: TestComponent = fixture.componentInstance;
});
If the TestService
requires any services, then you should add those also. If the TestService
requires Http
, then you need to mock the connection so that there is no real XHR request during the test. See link below for example
See Also:
Http
connections to provide mock responses.Upvotes: 3