【问题标题】:ng2-dragula unit test "dragulaService.setOptions is not a function"ng2-dragula 单元测试“dragulaService.setOptions 不是函数”
【发布时间】:2018-08-01 18:17:29
【问题描述】:

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

但是,当我对组件运行一个简单的单元测试时,我得到了错误

TypeError:无法读取未定义的属性“setOptions”

component.html

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

component.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');
      }
    });
  }

  ...
}

component.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 的单元测试并不那么在意;我想测试组件中的其他功能,但此错误不允许运行任何进一步的测试。

【问题讨论】:

    标签: angular unit-testing ng2-dragula


    【解决方案1】:

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

    { provide: DragulaService }

    那么您应该提及useClassuseValue 属性。

    例如:{ provide: DragulaService, useClass : MockService }

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多