【问题标题】:Mock a library directive from angular从角度模拟库指令
【发布时间】:2021-02-15 02:21:12
【问题描述】:

我想对使用库指令的组件进行单元测试。我的代码如下所示:

// component.spec.ts
@Directive({
    selector: 'mwlFlatpickr',
})
class mwlFlatpickr implements OnDestroy{
  @Input('mwlFlatpickr') public x: any;
  @Input('convertModelValue') public y: boolean;
  @Input('dateFormat') public z: string;
  public ngOnDestroy(): void {}
}

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        mwlFlatpickr
      ],
      imports: [
         // other modules
      ],
      providers: [
        // my services
      ]
    })
      .compileComponents();
  }));
  beforeEach(() => {
      fixture = TestBed.createComponent(CreateTaskComponent);
      component = fixture.componentInstance;
  });

html:

// component.html
 <input type="text" class="floating-label-field" mwlFlatpickr [convertModelValue]="true" dateFormat="d.m.Y" formControlName="dueDate">

我的问题是:组件使用了真正的 mwlFlatpickr,它在它的 onDestroy 中抛出了一个错误(组件实例没有定义,但这超出了我的测试范围)

 TypeError: Cannot read property 'destroy' of undefined
    at FlatpickrDirective.ngOnDestroy (angularx-flatpickr.js:330)
    at executeOnDestroys (core.js:14123)
    at cleanUpView (core.js:14030)
    at destroyViewTree (core.js:13799)
    at destroyLView (core.js:13981)
    at RootViewRef.destroy (core.js:14836)
    at ComponentRef$1.destroy (core.js:33986)
    at ComponentFixture.destroy (testing.js:423)
    at UserContext.<anonymous> (component.spec.ts:160)
    at ZoneDelegate.invoke (zone-evergreen.js:364)

错误发生在清理中,所以测试无关紧要。想象一下it就是:

 it('should not throw an error', () => {
    expect(component).toBeDefined();
 });

我有点傻眼。我发现的所有教程和主题都以这种方式解决了一个模拟指令(它适用于管道很好) 指令类声明为:

export declare class FlatpickrDirective implements AfterViewInit, OnChanges, OnDestroy, ControlValueAccessor

当然,我尝试将名称更改为该名称并实现了其他工具 - 同样的错误,组件不使用我的 mockDirective

【问题讨论】:

  • 你试过ng-mocks吗?帮助解决这个问题

标签: angular jasmine flatpickr


【解决方案1】:

它使用真正的mwlFlatpickr,因为我敢打赌你在TestBed.configureTestingModuleimports 数组中有FlatpickrModule,或者导入SharedModuleSharedModule,它使用实际实现而不是你的模拟提供。尝试从imports 中删除FlatpickrModule 或可疑的SharedModule

如果您不想从imports 中删除SharedModule,则必须使用overrideDirective 覆盖该指令。 https://angular-2-training-book.rangle.io/testing/components/injecting-dependencies/overriding

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2015-08-30
    • 2016-05-05
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多