Shweta Shetty
Shweta Shetty

Reputation: 11

Jasmine access protected property

I'm now to angular and have just completed my first implementation of angular inheritance.

I need to write a test case for the subclass where I cam assign value to protected variable (coming from base class ). This will help me test functionalities in the subclass.

Can someone please provide an example of how this spec.ts file can be written.

I'm wondering how the protected property can be accessed in the spec file of the subclass component.

Upvotes: 1

Views: 366

Answers (1)

Naren Murali
Naren Murali

Reputation: 57986

You need to access the property using the following syntax, please find below working example!

component

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';
}

test cases

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');
  }));
});

stackblitz

Upvotes: 1

Related Questions