如何在Angular指令中测试@Input的set方法

时间:2018-04-06 06:11:27

标签: angular karma-jasmine angular-test angular-testing

我是Angular测试的新手。我必须在Angular指令中测试@Input的set和get方法。但我不知道如何实现它。任何帮助表示赞赏。



import { Directive, Input, OnDestroy } from '@angular/core';

import {myService } from './../../../internal-service/myservice.service';

@Directive({
  selector: '[myDirectivekey]'
})
export class myDirective implements OnDestroy {
  private conf;

  @Input()
  set key(key) {
    if (key) {
      this.conf = key;
    }
  }

  get key() { return this.conf; }

  constructor(private myServic: myServic) { }

}




1 个答案:

答案 0 :(得分:2)

为简单起见,我只是创建一个新指令实例,因为您要测试setget,我将myServic设置为null

检查此测试

describe('should set conf', () => {
    const testDirective = new myDirective(null);

    const testValue = 'test';

    testDirective.key = testValue; // this will call set key
    expect(testDirective.key).toEqual(testValue); // this will call get key

    testDirective.key = null; // test whether if(key) works
    expect(testDirective.key).toEqual(testValue); // since, we just passed a null, it should not set the value.
});