【发布时间】: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吗?帮助解决这个问题