0

我是 Angular 测试的新手。我必须@Input在 Angular 指令中测试 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) { }

}

4

1 回答 1

2

为简单起见,我将只创建一个指令的新实例,并且由于您要测试setand get,因此我将其设置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.
});
于 2018-04-06T09:05:43.467 回答