【问题标题】:How to test the label of an input on angular 4+?如何在 Angular 4+ 上测试输入的标签?
【发布时间】:2019-09-08 05:07:48
【问题描述】:

我有一个形状像这样的角度组件:

<form>
  <label for="Name">Click me</label>
  <input type="text" id="Name" name="Name" />

  <label for="Name2">Click me 2</label>
  <input type="text" id="Name2" name="Name" />

</form>

我需要一个单元测试来验证 input[id=Name] 是否有一个带有文本的标签:“单击名称”。如何使用 jasmin 和 karma 对 Angular 进行单元测试?

【问题讨论】:

    标签: angular typescript unit-testing jasmine karma-jasmine


    【解决方案1】:

    获取元素并测试它。

    it('should check label name', () => {
        let labelName = fixture.debugElement.query(By.css("label[for=Name]"));
        expect(labelName.nativeElement.textContent).toBe("Click Me");
    })
    

    问题是如何与该元素交互,而不是如何测试它。

    祝你好运!

    【讨论】:

      【解决方案2】:

      您发布的代码有点混乱。 以下是测试标签的可能解决方案,无论是否输入。

      导入:

      从 '@angular/core/testing' 导入 { ComponentFixture, TestBed };

      从 '@angular/platform-b​​rowser' 导入 { By };

      代码:

      let fixture: ComponentFixture<YourComponent> = TestBed.createComponent(YourComponent);
      const queryValue = fixture.debugElement.query(By.css('#your-label-id'));
      
      expect(queryValue).toBeTruthy();
      expect(queryValue.nativeElement).toBeTruthy();
      expect(queryValue.nativeElement.outerText).toContain("Text expected in the label");
      

      【讨论】:

        猜你喜欢
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 2018-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-07-30
        相关资源
        最近更新 更多