2016-11-17 84 views
1

我正在尝试做angular2测试并遇到问题。我正在尝试在HTML中测试绑定。简要的代码如下所示:Angular 2测试组件html

组件:

export class NavbarComponent { 
    projectName = "Quiz!" 
} 

模板:

<a class="navbar-brand" routerLink="/intro">{{projectName}}</a> 

我一直努力遵循在线的例子,我已经尝试过这样做的以下几个方面:

describe('NavBar component',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [NavbarComponent], 
     }); 
    }); 
}); 

it('should contain the projectName variable',() => { 
    let fixture = TestBed.createComponent(NavbarComponent); 
    fixture.detectChanges(); 

    let nav = fixture.nativeElement 
    let title = nav.querySelectorAll('.navbar-brand'); 

    expect(title.textContent).toContain(nav.projectName); 
}); 

该方法给出此错误:错误:无法创建组件NavbarComponent因为它没有被导入到测试模块中!

我曾尝试第二种方法:

let fixture: ComponentFixture<NavbarComponent>; 
let component: NavbarComponent; 
let debug: DebugElement; 
let element: HTMLElement; 

describe('NavBarComponent',() => { 
    beforeEach(() => { 
     TestBed.configureTestingModule({ 
      declarations: [NavbarComponent] 
     }); 
    }); 

    fixture = TestBed.createComponent(NavbarComponent); 
    component = fixture.componentInstance; 

    debug = fixture.debugElement.query(By.css('.navbar-brand')); 
    element = debug.nativeElement 

}); 

describe('navbar title check, project name variable', function() { 
    it('should be Quiz!', function() { 
     fixture.detectChanges(); 
     expect(element.textContent).toContain(component.projectName); 
    }); 
}); 

对于这种方法,我得到以下错误:类型错误:无法读取的不确定

财产“detectChanges”我是新来的编程更不用说测试,所以任何帮助将不胜感激。谢谢

+0

您是否在测试文件中使用了'filepath'中的导入{NavbarComponent} – Anil

回答

0

把所有东西都放入describe,摆脱第二个describe并把it放在第一个里面。同时所有的任务应该去beforeEach

describe('',() => { 
    let someVar; 

    beforeEach(() => { 
    TestBed.configureTestingModule({}); 
    someVar = whatever; 
    }) 

    it('',() => { 

    }) 
}) 

这应该让你开始内部。