Jasmine 访问受保护的属性

问题描述 投票:0回答:1

我现在转向 Angular,刚刚完成了我的第一个 Angular 继承实现。

我需要为子类编写一个测试用例,在其中我可以为受保护的变量(来自基类)赋值。这将帮助我测试子类中的功能。

有人可以提供一个如何编写此spec.ts 文件的示例吗?

我想知道如何在子类组件的spec文件中访问受保护的属性。

angular inheritance jasmine subclass protected
1个回答
0
投票

您需要使用以下语法访问该属性,请参阅下面的工作示例!

组件

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  private test = 'test';
  protected test1 = 'test1';
  public test2 = 'test2';
}

测试用例

import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { TestBed, async } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';

describe('AppComponent', () => {
  beforeAll(() => {
    TestBed.initTestEnvironment(
      BrowserDynamicTestingModule,
      platformBrowserDynamicTesting()
    );
  });
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [AppComponent],
    }).compileComponents();
  }));
  it("should render title 'Welcome to app!!' in a h1 tag", async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain(
      'Welcome to app!!'
    );
  }));
  it('should check private property', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.componentInstance;
    expect(compiled['test']).toEqual('test');
  }));
  it('should check protected property', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.componentInstance;
    expect(compiled['test1']).toEqual('test1');
  }));
  it('should check public property', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.componentInstance;
    expect(compiled.test2).toEqual('test2');
  }));
});

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.