0

I am trying to test @Input in angular 2 .@Input hide or show my p tag .I want to test this functionality using jasmine.

here is my component

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';
  @Input() enable:boolean
  constructor() { }
}

testing code.

describe('@Input property ', () => {
    it('will not show p tag', () => {
      component.enable = false;
      fixture.detectChanges();
      PEl = fixture.debugElement.query(By.css('p'));
      console.log(PEl.nativeElement);
      expect(PEl.nativeElement.length).toEqual(0);
    })
  })

https://stackblitz.com/edit/angular-testing-wzxrin?file=app%2Fapp.component.spec.ts

6
  • 1
    If you use *ngIf and it's false then the element will not be rendered to the dom tree. So your PEl = fixture.debugElement.query(By.css('p')); returns nothing... that is what you would have to check in your test. Commented May 28, 2018 at 6:09
  • @Fussel what is condition for that Commented May 28, 2018 at 6:16
  • i checked it's length is 0 but it not works for me Commented May 28, 2018 at 6:16
  • It has no length, it will be null Commented May 28, 2018 at 6:24
  • stackblitz.com/edit/… Commented May 28, 2018 at 6:26

2 Answers 2

1

Test if it's null, not if it has length.

component.enable = false;
fixture.detectChanges();
PEl = fixture.debugElement.query(By.css('p'));
console.log(PEl.nativeElement);
expect(PEl).toBeUndefined();
Sign up to request clarification or add additional context in comments.

5 Comments

what about when enable is true
expect(PEl).not.toBeUndefined()
see your test is failing
0

Test for null not for length

component.enable = false;
fixture.detectChanges();
PEl = fixture.debugElement.query(By.css('p'));
expect(PEl).tobeNull();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.