Как выполнить модульный тест для @ouput с тестовыми данными, Angular 8? - PullRequest
0 голосов
/ 09 мая 2020

Я пытаюсь написать модуль жасмина для ниже testComponent . Это моя первая попытка написать модульные тесты.

Здесь я пытаюсь передать объект через событие click . но есть небольшая путаница в настройке тестовых данных с той же структурой в файле spec.ts.

При нажатии ng test я получаю position из undefined

Пока что я сделал как показано ниже

<button (click)="clickToCheck();"> </button>

testComponent.ts

export class testComponent implements  {

  @Output() passVal = new EventEmitter();
  @Input() checkEmployeePosition: any;

 clickToCheck() {
    const testData = {
      position: this.checkEmployeePosition.level
    };
    this.passVal.emit(testData);
  }
}

testComponent.spe c .ts

import { DebugElement, ElementRef } from "@angular/core";
import {
  TestBed,
  ComponentFixture,
  fakeAsync,
  tick,
} from "@angular/core/testing";
import { By } from "@angular/platform-browser";
import { testComponent } from "./testComponent.component";
import { fileURLToPath } from "url"

fdescribe("testComponent", () => {
  let fixture: ComponentFixture<testComponent>;
  let component: testComponent;
  let de: DebugElement;
  let btn: ElementRef;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [testComponent],
    });
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(testComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    btn = de.query(By.css("button"));
  });

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

  describe("passVal", () => {

    /*
    let testData = {
        name : 'hell0 world'
    }
    */
    it("should emit when the button is clicked", () => {
      spyOn(component.passVal, "emit");
      btn.nativeElement.click(); 
      expect(component.passVal.emit).toHaveBeenCalledWith(1);
    });
    it("should emit when clickToCheck() is called", () => {
      spyOn(component.passVal, "emit");
      component.emitContinue(); 
      expect(component.passVal.emit).toHaveBeenCalledWith(1);
    });
    it("should emit when the button is clicked", () => {
      component.passVal.subscribe((next: any) => {
        expect(next).toEqual(1);
      });
      btn.nativeElement.click();
    });
  });
});

Пожалуйста, помогите мне в этом.

Всем спасибо

Ответы [ 2 ]

0 голосов
/ 09 мая 2020
it('should emit when the button is clicked', () => {
    let expected;

    component.checkEmployeePosition = {level: 'top'};
    fixture.detectChanges();

    component.passVal.subscribe(data => expected = data);

    btn.nativeElement.click();

    expect(expected).toEqual({ position: 'top' });
});

или

it('should emit when the button is clicked', () => {
    spyOn(component.passVal, 'emit');

    component.checkEmployeePosition = {level: 'top'};
    fixture.detectChanges();

    btn.nativeElement.click();

    expect(component.passVal.emit).toHaveBeenCalledWith({ position: 'top' });
});
0 голосов
/ 09 мая 2020

Ваш последний тест - единственный, который вам нужен, но не забудьте инициализировать checkEmployeePosition и добавить готово:

    it("should emit when the button is clicked", done => {
      component.checkEmployeePosition = {level: 'dummy'};
      component.passVal.subscribe((next: any) => {
        expect(next).toEqual(1);
        done();
      });
      btn.nativeElement.click();
    });

Другой способ проверить это - поместить TestComponent внутрь компонента хоста, чтобы присвоить Input() checkEmployeePosition значение.

...