我想在具有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添加为提供程序以在组件的构造函数中使用它呢?
我看过{em> 似乎与之相关的Angular2 unit testing : testing a component's constructor,但我无法解决该错误。
注意:我对单元测试Dragula并不那么困惑;我想测试组件中的其他功能,但是此错误不允许运行任何进一步的测试。
答案 0 :(得分:0)
更改提供DragulaService
的方式。如果您提供
{ provide: DragulaService }
然后您应该提及其useClass
或useValue
属性。
例如:{ provide: DragulaService, useClass : MockService }
如果您不想模拟,则直接将其添加到providers
数组中。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ],
providers: [
DragulaService // see this line
]
})
.compileComponents();
}));