【问题标题】:Test method setter @Input() Angular 4 Karma测试方法设置器 @Input() Angular 4 Karma
【发布时间】:2018-02-08 09:31:38
【问题描述】:

如何从组件中测试此方法:

@Input() set camera(camera: CameraModel) {
    this._camera = camera;
    if (this._camera && this._camera.cameraId) {
        this.fetchVideos(this._camera);
    }
}

在测试中,你需要把我的stub给他,但是由于我没有尝试过,它不起作用......

信息

如果我在测试中使用 setter 作为方法,我会收到错误“component.camera is not a function”

TypeError: component.camera is not a function
at Object.eval (webpack:///D:/dev/nighthawk/frontend/src/app/components/dashboard-videos-list/dashboard-videos-list.component.spec.ts?:86:23)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:392:26)
at AsyncTestZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/async-test.js?:49:39)
at ProxyZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/proxy.js?:76:39)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:391:32)
at Zone.runGuarded (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:155:47)
at runInTestZone (webpack:///D:/dev/nighthawk/frontend/~/@angular/core/@angular/core/testing.es5.js?:128:25)
at Object.eval (webpack:///D:/dev/nighthawk/frontend/~/@angular/core/@angular/core/testing.es5.js?:67:13)
at ZoneDelegate.invoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/zone.js?:392:26)
at ProxyZoneSpec.onInvoke (webpack:///D:/dev/nighthawk/frontend/~/zone.js/dist/proxy.js?:79:39)

在每个之前测试:

beforeEach(() => {
    fixture = TestBed.createComponent(DashboardVideosListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

测试:

describe('set camera', () => {
    it('success', async(() => {
        component.camera(new CameraModel({
            cameraId: 13
        }));

        expect(component._camera['cameraId']).toBe(13);
    }));
});

【问题讨论】:

  • 您需要提供更多信息。什么不起作用,你看到什么错误?如何在测试中设置输入属性?你如何测试它的设置?

标签: angular unit-testing testing karma-runner


【解决方案1】:

代替

   component.camera(new CameraModel({
       cameraId: 13
   }));

你想要的

component.camera = new CameraModel({});

由于它是一个输入设置器,因此您并没有真正调用该函数,而是每次给它一个新值时该函数都会运行。 (:

【讨论】:

  • 它不适合我
猜你喜欢
  • 2017-12-01
  • 1970-01-01
  • 2019-03-23
  • 2018-03-01
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多