Home > Mobile >  Test Jest Angular : Can't bind to innerText since it isn't a known property of div
Test Jest Angular : Can't bind to innerText since it isn't a known property of div

Time:10-25

Considering the following Angular component :

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

@Component({
  selector: 'form-value',
  templateUrl: './form-value.component.html',
  styleUrls: ['./form-value.component.scss'],
})
export class FormValueComponent {
  @Input() label!: string;
  @Input() value!: unknown;
}

and its template

<div >
  <span > {{ label }} </span>
  
  <div  [innerText]="value"></div>
</div>

I use innerText because I need the displayed text to take \n line returns in consideration. Which is not the case with just {{ value }}.

The problem is that when I execute the following JEST test for the component :

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { FormValueComponent } from './form-value.component';
import { SharedModule } from '../../shared.module';
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('FormValueComponent', () => {
  let component: FormValueComponent;
  let fixture: ComponentFixture<FormValueComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [FormValueComponent],
      imports: [CommonModule],
    }).compileComponents();

    fixture = TestBed.createComponent(FormValueComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I have the following error :

Error: NG0303: Can't bind to 'innerText' since it isn't a known property of 'div' (used in the 'FormValueComponent' component template).

  1. If 'div' is an Angular component and it has the 'innerText' input, then verify that it is a part of an @NgModule where this component is declared.
  2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.

This is an error that often appears when a module is missing from the imports from TestBed, but I can't find which module innerText comes from. How to fix this properly ?

The only option that I thought of for now was to add schemas: [NO_ERRORS_SCHEMA] to my TestBed configure but it's not working as well ! Same error ! I have also tried innerText="{{value}}" instead of [innerText]="value"

CodePudding user response:

It's working with [attr.innerText] instead of [innerText] !

I still don't think this is normal behavior so I opened an issue on GitHub I'll update here when there's an answer

  • Related