我是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) { }
}

答案 0 :(得分:2)
为简单起见,我只是创建一个新指令实例,因为您要测试set
和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.
});