Ошибка с угловым модульным тестом ElementRef с Jest

У меня есть ошибка, когда я запускаю модульные тесты с помощью Jest, у меня есть компонент для приложения в Angular, когда у меня есть в конструкторе 'ElementRef', он выдает следующую ошибку:

Incrementador Component › should create

Can't resolve all parameters for IncrementadorComponent: (?).

  at syntaxError (../packages/compiler/src/util.ts:108:17)
      at Array.forEach (<anonymous>)
      at Array.forEach (<anonymous>)
  at src/app/recovered/components/incrementador/incrementador.component.spec.ts:28:8
  at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:386:30)
  at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:117:43)     
  at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:385:36)
  at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone.js:143:47)

Тест проходит без проблем до тех пор, пока у вас нет параметра ElementRef в конструкторе. Но когда я его ставлю, тест завершается ошибкой, указанной выше: Cannot resolve all parameters for IncrementadorComponent: (?).

import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';

@Component({
  selector: 'app-incrementador',
  templateUrl: './incrementador.component.html',
  styleUrls: ['./incrementador.component.scss']
})
export class IncrementadorComponent implements OnInit {

  @ViewChild('txtProgress') txtProgress: ElementRef;

  @Input('nombre') leyenda: string = 'Leyenda';
  @Input() progreso: number = 50;

  @Output('actualizaValor') cambioValor: EventEmitter<number> = new EventEmitter();

  constructor( private elementRef: ElementRef) { }
  // constructor( ) { }

  ngOnInit() { }

  onChanges( newValue: number ) {

    if ( newValue >= 100 ) {
      this.progreso = 100;
    }else if ( newValue <= 0 ) {
      this.progreso = 0;
    }else {
      this.progreso = newValue;
    }
    this.txtProgress.nativeElement.value = this.progreso;
    this.cambioValor.emit( this.progreso );
  }

  cambiarValor( valor: number ) {

    if ( this.progreso >= 100 && valor > 0 ) {
      this.progreso = 100;
      return;
    }
    if ( this.progreso <= 0 && valor < 0 ) {
      this.progreso = 0;
      return;
    }
    this.progreso = this.progreso + valor;
    this.cambioValor.emit( this.progreso );
  }
}
import { ComponentFixture, inject, TestBed } from '@angular/core/testing';

import { IncrementadorComponent } from './incrementador.component';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { ElementRef, NO_ERRORS_SCHEMA } from '@angular/core';

export class MockElementRef extends ElementRef {
  constructor() { super(undefined); }
}


describe('Incrementador Component', () => {
  let component: IncrementadorComponent;
  let fixture: ComponentFixture<IncrementadorComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ IncrementadorComponent ],
      imports: [ FormsModule ],
      providers: [
        {
          provide: ElementRef,
          useClass: MockElementRef
        }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();
    fixture = TestBed.createComponent(IncrementadorComponent);
    component = fixture.componentInstance;
  });

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

Уточняю, что с Жасмин и Кармой такого не бывает. Это просто происходит со мной с Джест.


person mpuertao    schedule 02.02.2021    source источник


Ответы (1)


РЕШЕНО!!!

Привет, вот 2 вещи, чтобы решить вашу проблему:

  • Всегда запускайте ngcc перед запуском тестов. Это необходимо для того, чтобы Angular использовал правильный компилятор Ivy.
  • Установите emitDecoratorMetadata: true в файле tsconfig.spec.json.

Благодаря https://github.com/ahnpnl

https://github.com/thymikee/jest-preset-angular/issues/774#issuecomment-772881086-

person mpuertao    schedule 04.02.2021