Угловое модульное тестирование - макет дочернего компонента с использованием заглушки - PullRequest
2 голосов
/ 11 декабря 2019

Я пытаюсь выполнить модульное тестирование компонента, у которого есть дочерний компонент, который я хочу смоделировать. Я не хочу использовать NO_ERRORS_SCHEMA, потому что это связано с недостатками. Я пытаюсь использовать заглушку / фиктивный дочерний компонент. Код выглядит следующим образом:

parent.component.ts

@Component({
  selector: 'parent',
  template: `
    <!-- Does other things -->
    <child></child>
  `
})
export class ParentComponent { }

child.component.ts

@Component({
  selector: 'child',
  template: '<!-- Does something -->'
})
export class ChildComponent {
  @Input() input1: string;
  @Input() input2?: number;
}

parent.component.spec.ts

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;
  let router: Router;

  @Component({
    selector: 'child',
    template: '<div></div>'
  })
  class ChildStubComponent {
    @Input() input1: string;
    @Input() input2: number;
  }

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ParentComponent, ChildStubComponent ],
      imports: [
        AppRoutingModule, HttpClientModule, BrowserAnimationsModule,
        RouterTestingModule.withRoutes(routes)
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router);
    spyOnProperty(router, 'url', 'get').and.returnValue('/somePath');
    fixture.detectChanges();
  });

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

Проблема, с которой я сталкиваюсь, заключается в том, что angular жалуется на следующую ошибку:

Failed: Template parse errors:
More than one component matched on this element.
Make sure that only one component's selector can match a given element.

IЯ использую Angular версии 8, если это помогает. Везде, где я смотрел до сих пор, видно, что вы заглушаете дочерний компонент так же, как я сейчас. Использование ngMocks на данный момент не вариант.

EDIT Пробовал с использованием ngMock, но это имеет ту же проблему. Любая помощь будет принята с благодарностью!

Решение

Работает. Проблема заключалась в том, что AppRoutingModule уже импортировал реальный компонент.

1 Ответ

0 голосов
/ 11 декабря 2019

Для вложенного компонента мы можем имитировать их следующим образом: https://angular.io/guide/testing#stubbing-unneeded-components

В заключение, ваш parent.component.spec.ts должен быть:

import { HttpClientTestingModule} from '@angular/common/http/testing';
import { Component } from '@angular/core';

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;
  let router: Router;


 @Component({selector: 'child', template: ''})
 class ChildStubComponent {}

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ParentComponent, ChildStubComponent ],
      imports: [
        AppRoutingModule, HttpClientTestingModule, BrowserAnimationsModule,
        RouterTestingModule.withRoutes(routes)
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router);
    spyOnProperty(router, 'url', 'get').and.returnValue('/somePath');
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...