首页 > 解决方案 > Angular - 使用附加的集合测试@Input

问题描述

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

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

<spinner small></spinner>

然后我将此作为一个@Input(<size>)并执行一个设置来更改一个大小变量,然后将其传递给一个[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;
}

组件.html

<div [ngStyle]="getSize"></div>

我已经成功测试了这个get getSize()功能,但是我对这些功能有点卡住了@Input(<val>) set:-/

标签: javascriptangulartypescripttestingkarma-runner

解决方案


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

我的 [feature/component/service/function/variable/...] 有什么作用?

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

作为带有Input装饰器的设置器,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);
});

推荐阅读