angular - ng2-dragula 单元测试 "dragulaService.setOptions is not a function"

标签 angular unit-testing ng2-dragula

我想在具有 ng2-dragula 的组件上运行单元测试。

但是,当我对组件运行简单的单元测试时,出现错误

TypeError: Cannot read property 'setOptions' of undefined

组件.html

<div [dragula]="'section-bag'"
     [dragulaModel]='form.sections'>
  <div *ngFor="let section of form.sections">
    <div class="drag-handle__section"></div>
  </div>
</div>

组件.ts

import { Component, Input } from '@angular/core';
import { DragulaService } from 'ng2-dragula';
...


export class MyComponent {

  @Input() form;

  constructor(private dragulaService: DragulaService) {
    dragulaService.setOptions('section-bag', {
      moves: (el, container, handle) => {
        return handle.classList.contains('drag-handle__section');
      }
    });
  }

  ...
}

组件.spec.ts

import { DragulaService } from 'ng2-dragula';
...


describe('Test for MyComponent', () => {
  let comp: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [
        { provide: DragulaService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
    comp.form.sections = [];
    comp.form.sections.push(new FormSection());

    fixture.detectChanges();
  });

  it('should create', () => {
    expect(comp).toBeTruthy();
  });

});

我猜 Dragula 没有正确导入,那么如何在测试中添加 Dragula 作为提供者以在组件的构造函数中使用它?

我看过Angular2 unit testing : testing a component's constructor似乎相关,但我无法解决该错误。

注意:我对 Dragula 单元测试并不那么在意;我想测试组件中的其他功能,但此错误不允许运行任何进一步的测试。

最佳答案

改变您提供DragulaService的方式。如果你提供像

{ 提供:DragulaService }

那么您应该向其提及 useClassuseValue 属性。

例如:{提供:DragulaService,useClass:MockService}

如果你对mock不感兴趣,那么直接将其添加到providers数组中。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [
         DragulaService  // see this line
      ]
    })
    .compileComponents();
}));

关于angular - ng2-dragula 单元测试 "dragulaService.setOptions is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51630753/

相关文章:

angular - ng2-dragula setOptions 和 drop 版本问题

angular - 未捕获的 TypeError : ctorParameters. map 不是函数

angular - 将数据(从后端)解析为根组件

java - 有什么简单的方法可以将字符串从 JavaEE 后端推送到 Javascript 客户端吗?

javascript - Angular 中带有关键字标签的文本区域

unit-testing - 你如何从 Rhino.Commons 模拟 UnitOfWork?

rxjs - 拖放自动滚动(dom-autoscrolling)

Angular 类绑定(bind)

java - 测试网络应用程序

unit-testing - 使用 InMemoryTestFixture 测试 MassTransit Consumer