Angular 2测试组件html

时间:2016-11-17 12:13:56

标签: unit-testing angular karma-jasmine

我正在尝试进行angular2测试并遇到问题。我试图在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);
    });
});

对于此方法,我收到以下错误:TypeError:无法读取未定义的属性'detectChanges'

我是编程的新手,更不用说测试了,所以任何帮助都会非常感激。感谢

1 个答案:

答案 0 :(得分:0)

将所有内容放入describe,然后删除第二个describe并将it置于第一个beforeEach内。此外,您的所有作业都应该放在describe('', () => { let someVar; beforeEach(() => { TestBed.configureTestingModule({}); someVar = whatever; }) it('', () => { }) })

gulp.task('compile', function () {
  return gulp.src(['typings/index.d.ts', 'src/*.ts', 'spec/*.ts'])
    .pipe(typescript()).pipe(gulp.dest('dist/js/'));
});

gulp.task('test', function () {
  return gulp.src('dist/js/spec/test.js')
    .pipe(jasmine());
});

//http://stackoverflow.com/a/26390567/2777965
gulp.task('default', ['compile', 'test']);

这应该让你开始。