Тест Angular Integration: тестирование функции, которая вызывается при отправке события из другого компонента. Как мне посмеяться над данными события? - PullRequest
0 голосов
/ 20 ноября 2018

В моем компоненте A у меня есть функция, которая обновляет представление на основе данных, излучаемых компонентом B. Я не хочу интегрировать компонент B и создавать фактическое значение, даже если это слишком сложно для этого теста.

Я просто хочу вызвать функцию и передать данные в функцию. Проблема в том, что отправка данных как «событие» в функцию в компоненте A, похоже, не работает:

  it('should update the video with the data from the edit component', () => {
    let event;
    event.title = 'New Title';
    event.description = 'New Description';
    event.link = 'New Link';
    event.videoCategory = 'New Category';
    event.categories = '2';
    event.a14Only = 0;

    component.updateVideoCard(event);
    fixture.detectChanges();

    expect(component.videoTitle).toBe('New Title');
    expect(component.videoLink).toBe('New Link');
    expect(component.videoDescription).toBe('New Description');
    expect(component.videoCategory).toBe('New Category');
    expect(component.categoryID).toBe('2');
    expect(component.a14Only).toBe('0');
    expect(component.editDisabled).toBeTruthy();
  });

и это событие заканчивается как «неопределенное». Я также попытался сделать из него объект javascript с именем 'event', в котором есть пары ключ-значение, но это также не принесло удачи.

код component.updateEvent (data):

updateVideoCard(event) {
    this.videoTitle = event.title;
    this.videoDescription = event.description;
    this.videoLink = event.link;
    this.videoCategory = event.category;
    this.categoryID = event.categories;
    if (event.a14Only === 1) {
      this.a14Only = true;
    } else {
      this.a14Only = false;
    }
    this.enableEditor = false;
    this.notification.done(`${this.videoTitle} updated successfully.`);
  }

1 Ответ

0 голосов
/ 20 ноября 2018

Я посмотрел на DebugElement.triggerEvent, но, к сожалению, документация устарела и мне не повезло, я сам понял, как это сделать.Похоже, что в любом случае также требовалось интегрировать второй компонент.

В итоге я интегрировал 2 компонента и просто запустил его с помощью стандартного объекта JSON из второго компонента, например:

describe('VideoCardComponent', () => {
  let component: VideoCardComponent;
  let fixture: ComponentFixture<VideoCardComponent>;
  let fixture2: ComponentFixture<EditVideoComponent>;
  let component2: EditVideoComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        MatCardModule,
        MatButtonModule,
        BrowserAnimationsModule,
        FontAwesomeModule,
        BrowserModule,
        FlexLayoutModule,
        RouterTestingModule,
        ReactiveFormsModule,
        FormsModule,
        MatSelectModule,
        MatOptionModule,
        MatInputModule,
        MatSlideToggleModule
      ],
      declarations: [VideoCardComponent, SafepipePipe, EditVideoComponent],
      providers: [
        { provide: RestService, useClass: RestStub },
        { provide: NotificationService, useClass: NotificationStub }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
      .compileComponents()
      .then(() => {
        fixture2 = TestBed.createComponent(EditVideoComponent);
        fixture = TestBed.createComponent(VideoCardComponent);
        component = fixture.componentInstance;
        component2 = fixture2.componentInstance;
        fixture2.detectChanges();
        fixture.detectChanges();
      });
  }));

Вывидно, что я просто назвал его component2 и fixture2 и добавил зависимости для обоих в одном и том же тестовом стенде 1.

Я, вероятно, назову их чем-то более актуальным, вместо component и component2.

фиксированный тест:

it('should update the video with the data from the edit component', () => {
    const data = [
      {
        title: 'New Title',
        description: 'New Description',
        link: 'New Link',
        category: 'New Category',
        categories: '2',
        a14Only: 0
      }
    ];

    component2.updateVideoCard.subscribe(newVideo => {
      component.updateVideoCard(newVideo);
      expect(component.videoTitle).toBe('New Title');
      expect(component.videoLink).toBe('New Link');
      expect(component.videoDescription).toBe('New Description');
      expect(component.videoCategory).toBe('New Category');
      expect(component.categoryID).toBe('2');
      expect(component.a14Only).toBeFalsy();
      expect(component.editDisabled).toBeFalsy();
    });

    component2.updateLocalVideoData(data);

    fixture2.detectChanges();
    fixture.detectChanges();
  });
...