【问题标题】:How to solve the InvalidPipeArgument 'AsyncPipe' error in Angular unit testing?如何解决 Angular 单元测试中的 InvalidPipeArgument 'AsyncPipe' 错误?
【发布时间】:2020-08-03 20:41:05
【问题描述】:

当我在模板中使用| async 管道时,我在单元测试中收到InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' 错误。

尝试使用 tick, fakeAsync and whenStable 解决此问题,但没有成功。

当我删除模板中的| async 部分时,错误消失并且单元测试可以工作,但这次代码不起作用。我需要在模板中使用| async 来让代码工作。

我该如何解决这个InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' 错误?

模板:

<ngb-accordion  
    [closeOthers]="true"  
    [activeIds]="setActiveAcc()">
    <div *ngFor="let child of el?.children | async; let i = index">
        <ngb-panel id="{{(child?.value?.properties | async)?.style.includes('OpenAcc')}}-{{i}}">
            <ng-template ngbPanelHeader>
                <div class="d-flex align-items-center justify-content-between">
                    <button ngbPanelToggle class="btn btn-link container-fluid text-left">
                        {{ (child?.value?.properties | async)?.content}}
                    </button>
                </div>
            </ng-template>
            <ng-template ngbPanelContent>
                <tst-element [item]="child"></tst-element>
            </ng-template>
        </ngb-panel>
    </div>
</ngb-accordion>

组件:

export class AccComponent implements OnInit {
    constructor(
      public el: ItemModelTree
    ) {}

    @Input() childrens: Array<any> = [];

    ngOnInit() {
        this.el.children.pipe(
          mapObservableArray((children: ObservableTree<ItemModel>) => children.value.properties))
            .subscribe((props: Properties[]) => {
            this.childrens = props as any;
        });
    }

    setActiveAcc() {
        if (this.childrens.find((child: any) => child.style.includes('OpenAcc'))) {
          const activeAcc = this.childrens.findIndex((child: any) => child.style.includes('OpenAcc'));
          return 'true-' + activeAcc;
        } else {
            return 'false'
        }
    }
}

单元测试:

import { NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { ItemModelTree } from './core';
import { AccComponent } from './accordion.component';
import { of } from 'rxjs';

describe('accardion component', () => {
  const itemModel = {
    value: {
      name: 'accordion'
    },
    children: [
      {
        id: 'acc-1',
        value: {
          properties: [
            {
              content: 'test',
              style: ['OpenAcc']
            }
          ]
        }
      }
    ],
  };
  const mockTree = jasmine.createSpyObj('el', itemModel);
  mockTree.children = of(itemModel.children);
  
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [],
      declarations: [AccComponent],
      providers: [
        { provide: ItemModelTree, useValue: mockTree }
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  it('should set the activeAccordion to true', async () => {
    const fixture = TestBed.createComponent(AccComponent);
    const componentInst = fixture.componentInstance;

    (componentInst as any).tree = {
      children: of([
        {
          id: 'acc-1',
          value: {
            properties: [
              {
                label: 'test',
                styles: ['OpenAcc']
              }
            ]
          }
        }
      ])
    };

    fixture.detectChanges();
    
    
    expect(componentInst).toBeDefined();
    expect(componentInst.setActiveAcc()).toEqual('true-0');
  });
});

如何使用| async管道解决InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'错误?

【问题讨论】:

    标签: angular jasmine karma-jasmine angular-test


    【解决方案1】:

    itemModel 模拟中,您需要制作properties: of(/* your data */),因为模板中有这些行:child?.value?.properties | async

    【讨论】:

    • 属性在children.value.properties 中。我可以通过删除 async 并将 observables 转换为数组来解决这个问题。但我想使用 Observable。
    • 是的,它们应该是可观察的,因为在模板中您使用异步管道来访问它们的值
    • 问题出在你对itemModel 的模拟中,只需让properties 可观察,错误就消失了
    • 如何使属性成为可观察的?通过添加of ?
    • 是的,doc
    猜你喜欢
    • 2019-11-13
    • 1970-01-01
    • 2021-02-12
    • 2018-05-23
    • 1970-01-01
    • 2018-06-22
    • 2017-12-05
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多