Как покрыть функцию трубы RXJS в Jasmine?

Я хочу осветить функцию канала RXJS в Angular / Jasmine.

Я получаю такую ​​ошибку:

TypeError: this.element.children.pipe is not a function

Код:

ngOnInit() {
    this.element.children.pipe(
      mapObservableArray((children: ObservableTree<ItemModel>) => children.value.properties))
        .subscribe((props: Properties[]) => {
        // do something with the props or children
        this.childrenElements = props as any;
    });
}

Это гарантирует, что я могу получить значения дочерних элементов и сохранить их в this.childrenElements.

.spec файл:

import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { myComponent } from './my.component';

describe('myComponent', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [CommonModule],
      declarations: [myComponent],
      providers: [],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  it('should create the component', async () => {
    const fixture = TestBed.createComponent(myComponent);
    const componentInst = fixture.componentInstance;

    componentInst.childrenElements = [
      { name: 'name1' },
      { name: 'name2' }
    ];

    // when
    componentInst.ngOnInit();

    // then
    expect(componentInst).toBeDefined();
  });
});

Пытался заглушить: spyOn(componentInst.element.children, 'pipe').and.stub();

Но это не помогло.

This.element.children:  введите описание изображения здесь

Как я могу покрыть эту часть моего кода?


person Can    schedule 26.06.2020    source источник


Ответы (1)


Вы должны исключить наблюдаемые данные типа element.children (что бы это ни было).

Я впервые вижу mapObservableArray, поэтому предполагаю, что это внутренний оператор.

Пытаться:

import { of } from 'rxjs';
.....
 it('should create the component', async () => {
    const fixture = TestBed.createComponent(myComponent);
    const componentInst = fixture.componentInstance;

    (componentInst as any).element = {
      children: of(/* mock how the children property should look like */);
    };

    // when
    // componentInst.ngOnInit();
    // don't call ngOnInit directly, the first detectChanges will call ngOnInit for you
    fixture.detectChanges();

    // then
    expect(componentInst).toBeDefined();
  });

Если element.children является производным от другого наблюдаемого, вы должны имитировать другое наблюдаемое так же, как я показал вам, и он должен течь хорошо.

Изменить. Попробуйте назначить его объекту, как показано выше. Если элемент доступен только для чтения или является частным, то имитировать будет сложно. Попробуйте сделать (componentInst as any), хотя я не думаю, что это лучший способ. Возможно, удалите его частный или доступный для чтения аспект в целях тестирования. Снимок экрана, который вы мне прислали, представляет собой обернутый наблюдаемый объект, вы должны поместить развернутое значение внутри of.

person AliF50    schedule 26.06.2020
comment
Можете привести пример как поиздеваться? Я добавил скриншот element.children в первое сообщение. Когда я пытаюсь поиздеваться, я получаю (property) ObservableTree<ItemModel>.children: Observable<ObservableTree<ItemModel>[]> The children of this node Cannot assign to 'children' because it is a read-only property.ts(2540) - person Can; 29.06.2020
comment
Я добавил правку. Что такое this.element? Это объект? - person AliF50; 29.06.2020
comment
внутри this.element есть наблюдаемые. Теперь с вашим измененным кодом тест находится внутри трубы. Но на этот раз я получаю ошибку на реквизите. Uncaught TypeError: Cannot read property 'properties' of undefined thrown - person Can; 29.06.2020
comment
properties существует в element? А если так, вам придется так же издеваться над этим. - person AliF50; 29.06.2020