简体   繁体   中英

Creating an instance of a component: Angular2 unit testing

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM