如何在Angular指令中测试@Input的set方法 [英] How to test the set method of @Input in an Angular directives

查看:102
本文介绍了如何在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) { }

}

推荐答案

为简单起见,我将仅创建您指令的新实例,并且由于您要测试setget,因此我将设置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方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆