#testing @Input failed

8 messages · Page 1 of 1 (latest)

unkempt basin
#

Im testing @Input property from another component that has default value

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

export type Variant = 'primary' | 'secondary'

@Component({
  selector: 'my-button',
  standalone: true,
  template: `
    <button>
      <span>
        <ng-content></ng-content>
      </span>
    </button>
  `
})
export class MyButtonComponent {

  @Input() variant: Variant = 'primary'

}
import { Component } from '@angular/core';
import { TestBed, } from '@angular/core/testing';
import { MyButtonComponent } from './button.component';

import { By } from '@angular/platform-browser'

describe('MyButton', () => {

  it('should have default value for variant', () => {
    @Component({
      template: `
        <my-button>Hello</my-button>
      `,
      imports: [ MyButtonComponent ]
    })
    class TestComponent  {}

    const fixture = TestBed.createComponent(TestComponent)

    const button = fixture.debugElement.query(By.css('my-button')).nativeElement as MyButtonComponent
    
    /// since component property variant has default with primary 
    /// this should be passed 
    expect(button.variant).toEqual('primary')
  })

})
#

so why i doing test this?
its because i want to check if im using my component to another component it should have default value even if im not setting it the property

wind path
#

nativeElement returns the DOM element. Not the component instance. Instead, use

const button = fixture.debugElement.query(By.directive(MyButtonComponent)).componentInstance
unkempt basin
#

i tried it but componentInstance is undefined

#

it works now, i just put standalone: true in my TestComponent

#
const button = fixture.debugElement.query(By.css('my-button')).componentInstance as MyButtonComponent

this works also after adding standalone: true in my TestComponent

#

@wind path thanks for the idea 👍