0

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?

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

1 Comment

That helps, thanks! But when I tried creating a component with TestBed and then creating its instance by 'fixture.componentInstance', I still can't access the properties of the component with that instance. So if I have an integer variable called 'number' in the class definition of our component, i can't access 'number' with the instance we just created fixture.componentInstance in the spec file. Any suggestions on this?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.