【问题标题】:unit testing - Angular 6单元测试 - Angular 6
【发布时间】:2019-03-24 01:43:46
【问题描述】:

我正在做两个测试。

  1. 检查 h1 标签是否包含文本,即不为空。

  2. 检查h1标签是否包含title-icon /title-icon。

COMPONENT.SPEC.TS

<h1 class="head"><title-icon></title-icon>Confirmation</h1>

COMPONENT.HTML

import {async,ComponentFixture,TestBed} from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {ConfirmationDemoComponent} from './confirmation-demo.component';

describe('ConfirmationDemoComponent', () => {
    let component: ConfirmationDemoComponent;
    let fixture: ComponentFixture < ConfirmationDemoComponent > ;
    let compiled;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
                declarations: [ConfirmationDemoComponent],
                schemas: [CUSTOM_ELEMENTS_SCHEMA]
            })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ConfirmationDemoComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        compiled = fixture.debugElement.nativeElement;
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('-> should render text inside an h1 tag', async(() => {
        expect(compiled.querySelector('h1').textContent).not.toEqual(0);
    }));

    it('-> should render a <title-icon><title-icon> within an h1 tag', async(() => {

    }));
});

【问题讨论】:

    标签: angular typescript unit-testing jasmine


    【解决方案1】:

    检查h1标签中是否存在文本内容

    it('should render text inside an h1 tag', async(() => {
       // fetch debug element
       let h1El = fixture.debugElement.query(By.css('h1'));
       expect(h1El.nativeElement.textContent).not.toBeNull();
    }));
    

    要检查子标签title-icon是否存在于h1中,你可以这样

    it('should render a <title-icon><title-icon> within an h1 tag', async(() => {
       // fetch debug element
       let titleEl = fixture.debugElement.query(By.css('h1 title-icon'));
       expect(titleEl.nativeElement).toBeDefined();
    }));
    

    阅读有关DOM 测试的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 2017-04-04
      • 2016-12-29
      • 2021-02-12
      • 1970-01-01
      相关资源
      最近更新 更多