Angular - 测试一个附有集合的@Input

phy*_*boy 3 javascript testing typescript karma-runner angular

我有一个组件,它将参数作为一种指令来设置<div>其模板内的大小,现在唯一的问题是我不确定如何测试它?

我这样称呼我的组件,其中small可以替换为其他预定义的大小,例如medium/large等:

<spinner small></spinner>
Run Code Online (Sandbox Code Playgroud)

然后我将其作为 an@Input(<size>)并执行 set 以更改大小变量,然后将其传递给 an[ngStyle]以更改显示组件大小的 CSS。

组件.ts

size: number;

@Input('small') set small(value) {
  this.size = !value ? 25 : this.size;
}

get getSize() {
  const myStyle = {
    width: this.size + 'px',
    height: this.size + 'px'
  };
  return myStyle;
}
Run Code Online (Sandbox Code Playgroud)

组件.html

<div [ngStyle]="getSize"></div>
Run Code Online (Sandbox Code Playgroud)

我已经成功测试了该get getSize()功能,但我对这些功能有些困惑@Input(<val>) set:-/

小智 5

要知道要进行什么测试,请问自己这个问题:

我的 [功能/组件/服务/功能/变量/...] 做什么?

在这种情况下,您的二传手可以回答

作为带有Input装饰器的 setter,size如果我自己的值未定义,我应该设置变量的值。如果定义了我自己的值,我应该回退到默认值。

这意味着您的 setter 测试将如下所示:

it('should set size variable with value undefined', () => {
  component.size = 10;
  component.small = '';
  epxect(component.size).toEqual(25);
});

it('should not change size variable with value defined', () => {
  component.size = 10;
  component.small = 'ff';
  epxect(component.size).toEqual(10);
});
Run Code Online (Sandbox Code Playgroud)