Home > other >  Angular Unittest (jasmine, karma) how to test the @Input() is inserted to the html element
Angular Unittest (jasmine, karma) how to test the @Input() is inserted to the html element

Time:01-16

I'm writing some unit test for my register component. In this component i have a html Element:

<form  [formGroup]="registerForm">
    <mat-form-field>
         .....
    </mat-form-field>
   ...
</form>

I want to write 3 tests, first that checks the class of my form element, one that passes if registerForm isDefined and another one that passes if registerForm is injected to the form of .

My tests:

describe('register-form',() => {
   it('register-form should have class: register-form', () => {
     expect(registerForm.className).toBe('register-form');
   });
   it('component should have defined formGroup: registerForm', () => {
     expect(registerComponent.registerForm).toBeDefined();
   });
});

I'm missing the connection-test from registerForm => formGroup of my form element. How can I write this test?

Shortly: I wan't to access the Property formGroup of the HTMLElement .

CodePudding user response:

You can query the input element with a CSS selector and check the value of it.

it('register-form should have class: register-form', () => {
   let input = fixture.debugElement.query(By.css('input'));
   let el = input.nativeElement;

    expect(el.value).toBe('expected value');
});

more information is under: Angular Testing Documentation

CodePudding user response:

I just discovered the solution for my problem. I just create a mock for a hosting component.

describe('componentUnderTest', () => {
  @Component({
selector: `host-component`,
template: `<component-under-test [testInput]="testInput">
</component-under-test >`
 })
 class TestHostComponent {


       public testInput: string = '';
   } 
}

After that I created this test

it('deviceUnderTest should have @Input() decorator on testInput', () => {
        testHostComponent.testInput='testString';
        testHostFixture.detectChanges();
        expect(testHostFixture.debugElement.query(By.css('component-under-test'))
        .componentInstance['testInput']).toEqual('testString');
      });
  •  Tags:  
  • Related