Как проверить EventEmitter из сервиса - PullRequest
0 голосов
/ 14 июня 2019

Я новичок в Angular / Jasmine и мне нужна помощь, чтобы проверить немного спокойствия кода.

Мой файл ts createcustomer.ts Мой метод снимает логическое событие, которое прослушивается в другом компоненте.Мне нужно проверить, было ли отправлено событие ниже

export class CreateCustomerComponent {
  constructor(public breadCrumbService: BreadCrumbService) { }
  emit() {
    this.breadCrumbService.createCustomer$.emit(false)
  }
}

createcustomer.spec.ts Я хочу проверить мой метод выше

emit() {
  this.breadCrumbService.createCustomer$.emit(false)
}

Мой тестовый этап и я знаю, как проверить простой компонент emit в компоненте, но испуск службы, о которой я все еще знаю.

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [
        createCustomerComponent
      ],
      schemas: [
        NO_ERRORS_SCHEMA
      ],
      providers: [
        { provide: BreadCrumbService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CreateBotComponent);
    component = fixture.componentInstance;
  });

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

Я ожидаю createCustomer $ haveBeenCalledWith (false)

1 Ответ

0 голосов
/ 14 июня 2019
describe('CreateCustomerComponent ', () => {
  let component: CreateCustomerComponent ;
  let fixture: ComponentFixture<CreateCustomerComponent >;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      ...
      providers: [
        {
          provide: BreadCrumbService,
          // use can describe structure of mocked object with useValue or use declare mock class and bind it with useClass
          useValue: { createCustomer$: { emit: jasmine.createSpy('emit') } }
        }
      ]
    })
    .compileComponents();
  }));

  ...
  // what method do we test
  describe('.emit()', () => {
    // expected  behaviors
    it('should emit false via createCustomer$ from breadCrumbService', inject([BreadCrumbService], (service: BreadCrumbService) => {
      component.emit();// or you can play around and try to trigger it via template interactions
      expect(service.createCustomer$.emit).toHaveBeenCalledWith(false);
    }));
  });

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...