本文介绍了如何在Angular指令中测试@Input的set方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Angular测试的新手.我必须在Angular指令中测试@Input
的set和get方法.但是我不知道如何实现它.感谢您的帮助.
I'm new to Angular testing. I have to test the set and get method of @Input
in an Angular directive. But I have no idea on how to implement it. Any help is appreciated.
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) { }
}
推荐答案
为简单起见,我将仅创建您指令的新实例,并且由于您要测试set
和get
,因此我将设置myServic
为空.
For simplicity, I'll just create a new instance of your directive and since you want to test set
and get
, I'll set myServic
to 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.
});
这篇关于如何在Angular指令中测试@Input的set方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!