【问题标题】:Unit for testing string interpolation in Angular 4Angular 4中用于测试字符串插值的单元
【发布时间】:2020-03-26 12:58:31
【问题描述】:

在我的 HTML 中

<label>{{placeholder}}</label>

其中placeholder 是一个组件变量。如何使用 Jasmine 在 Angular 中测试字符串插值?

【问题讨论】:

    标签: angular jasmine angular-test


    【解决方案1】:

    如果您使用的是 Angular CLI,它会为您生成一个基本测试来执行此操作。

    <h1>{{ placeholder }}</h1>
    
    import { TestBed, async } from '@angular/core/testing';
    import { AppComponent } from './app.component';
    describe('AppComponent', () => {
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [
            AppComponent
          ],
        }).compileComponents();
      }));
      it('should render placeholder in a h1 tag', async(() => {
        const fixture = TestBed.createComponent(AppComponent);
        fixture.detectChanges();
        const compiled = fixture.debugElement.nativeElement;
        expect(compiled.querySelector('h1').textContent).toContain('my value');
      }));
    });
    

    【讨论】:

      【解决方案2】:

      你可以试试这个代码

      describe('WelcomeComponent', () => {
        let comp: any;
          beforeEach(() => {
            TestBed.configureTestingModule({
              // provide the component-under-test and dependent service
              declarations: [
                WelcomeComponent
              ]
            });
      
            fixture = TestBed.createComponent(WelcomeComponent);
            comp = fixture.componentInstance;
          });
      
          it('set placeholder some default value', () => {
            comp.placeholder = 'some text';
            expect(comp.placeholder).toContain('some text');
          });
      });
      

      【讨论】:

      • 您只想测试组件变量真是太好了。但是使用这种方法,您无法确定数据是否在 html 中正确呈现。通常我喜欢测试这两种方式。首先,您提出的,另一个是通过查询访问模板并从中提取值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2017-11-18
      • 2018-06-13
      • 1970-01-01
      • 2018-01-01
      相关资源
      最近更新 更多