AngularJS 2 unit testing component with jasmine facing error, Cannot read property 'firstChild' of null

I am writing unit test for my angular 2 application, I am trying to test the component I made. I am referring to a sample git repository for writing test cases in angular 2 using TypeScript and Jasmine framework. I did same what is done in sample repository ( to test my component but i get following error.

TypeError: Cannot read property 'firstChild' of null
at Object.el (
at TestComponentBuilder.createAsync (
at eval (
at FunctionWrapper.apply (
at FunctionWithParamTokens.execute (
at TestInjector.execute (
at Object.<anonymous> (
at attemptAsync (
at (

My component is like this:

  selector: 'search',
  templateUrl: 'app/html/search.component.html',
  styleUrls: ['app/css/search.css'],
  providers: [SearchService,SearchUtil],
  directives: [OverviewComponent]
export class SearchComponent {}

My unit test case looks like this:

it('should populate search suggestions UI', injectAsync([TestComponentBuilder,SearchComponent], (tcb) => {
    return tcb.createAsync(SearchComponent).then((fixture) => {
      var compiled = fixture.debugElement.nativeElement;


      var compiled = fixture.debugElement.nativeElement;

      console.log(compiled.querySelector('search').value()+" = "+compiled.querySelector('.searchlist>a').length);


I am getting error, in this line – tcb.createAsync(SearchComponent), says the object is null.

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
newest oldest most voted
Notify of

You don’t need to specify SearchComponent into the first parameter of the injectAsync function: it('should populate search suggestions UI', injectAsync([TestComponentBuilder], (tcb) => { return tcb.createAsync(SearchComponent).then((fixture) => { (...) }); })); Edit You also need to the base test providers, as described below: import {setBaseTestProviders} from 'angular2/testing'; import { TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS } from 'angular2/platform/testing/browser'; describe('Some tests', () => { setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS); (...) }); Edit1 You need to register the providers your component will use (directly or indirectly) using the beforeEachProviders function. Here is a sample: beforeEachProviders(() => { return [ HTTP_PROVIDERS, provide(XHRBackend, { useClass: MockBackend }), HttpService ]; });