18

I want to test the functionality of my hide-show button in my Angular 2 app(Tests are written in Jasmine), so I need to check the value of the display property of the relevant element. How can I get this property using Angular's debugElement? Test code:

let input = fixture.debugElement.query(By.css('input'));
expect(input.styles['visibility']).toBe('false');

I get the error: Expected undefined to be 'false'.

liorblob
  • 507
  • 1
  • 6
  • 19
  • Please check out [the documentation](https://angular.io/docs/ts/latest/guide/testing.html#simple-component-test)... It has code showing how to select a specific HTML in the template of the component under test. Then, it's only a matter of accessing this element's `style` property. – AngularChef Feb 01 '17 at 12:40
  • I get an error. See my edit above. – liorblob Feb 01 '17 at 12:53
  • @user6251216 - I think that If you want to access the HTML DOM Element Object you need to wrap it with nativeElement, like this: `let input = fixture.debugElement.query(By.css('input')).nativeElement`. – yl2015 Feb 20 '17 at 15:23
  • For this matter specifically I used the 'hidden' property on the debugElement. For other css classes the only thing that worked for me is the classList inside the nativeElement. The only downside of it that it has 'any' type. Anyway the whole thing involves a lot of voodoo. – liorblob Feb 20 '17 at 15:30
  • @user6251216 Could you not just cast. ie as HTMLInputElement or input – JGFMK Jul 29 '17 at 09:37

2 Answers2

7

I was having the same issue. The DebugElement.styles is always an empty object even if I set some style to that element explicitly(maybe bug in angular code?). So I would rather get that from the browser native element directly:

let input = fixture.debugElement.query(By.css('input'));
expect(input.nativeElement.style.visibility).toBe('false');
LeOn - Han Li
  • 9,388
  • 1
  • 65
  • 59
  • @AlexanderVolkov, then you have to make sure you have the `input` element(or any other `selectors`) in your DOM so that angular can find it and get its `nativeElement` afterwards. – LeOn - Han Li Oct 09 '20 at 22:01
2

For anyone stumbling upon this example, the solution for this specific issue with display is the hidden property on the debugElement. It will contain true if the element is hidden and false otherwise.

liorblob
  • 507
  • 1
  • 6
  • 19
  • 1
    Does not work for me: `Property 'hidden' does not exist on type 'DebugElement'. at Compiler.compiler.plugin (C:\Users\...\node_modules\@angular\cli\plugins\karma-webpack-throw-error.js:10:23)` – Florian Gössele Nov 21 '17 at 08:23
  • Try accessing the classList property of the nativeElement property in the debugElement – liorblob Dec 03 '17 at 08:30