【问题标题】:Angular 2 testing component htmlAngular 2 测试组件 html
【发布时间】:2016-11-17 12:13:56
【问题描述】:

我正在尝试进行 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: Cannot read property 'detectChanges' of undefined

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

【问题讨论】:

  • 你是否在测试文件中使用 import {NavbarComponent} from 'filepath'

标签: unit-testing angular karma-jasmine


【解决方案1】:

将所有内容放入describe,去掉第二个describe,将it 放入第一个。此外,你所有的作业都应该放在beforeEach

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

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

  it('', () => {

  })
})

这应该让你开始。

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2017-06-08
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2017-11-19
    • 2019-05-19
    • 1970-01-01
    相关资源
    最近更新 更多