我有一个组件,它将一个参数作为一种指令来设置其模板中<div>
的大小,现在唯一的问题是我不确定如何测试它?
我这样称呼我的组件,其中small
可以替换为其他预定义的大小,如medium/large
等:
<spinner small></spinner>
然后我将其作为@Input(<size>)
并执行一组更改大小变量,然后传递给[ngStyle]
以更改显示的组件大小的CSS。
component.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;
}
component.html
<div [ngStyle]="getSize"></div>
我已经成功测试了get getSize()
函数,但我已经变得有点卡在@Input(<val>) set
函数: - /
要知道要做什么测试,请问自己这个问题:
我的[feature / component / service / function / variable / ...]有什么作用?
在这种情况下,您的二传手可以回答
作为具有
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);
});
为了spyOn getter / setter属性,你可以使用jasmine spyOnProperty:
所以在你的例子中我们有:obj -> component, propertyName -> 'small', accessType -> 'set'
:
it('call small setter method', () => {
const small = spyOnProperty(component, 'small', 'set'); // just spyOn setter method of small
component.size = 10; // set initial value of size to 10
component.small = 'large'; // set small property which as expected - should call setted method
// we expect that `small` setter method will be called
// with 'large' argument, since we setted it before
expect(small).toHaveBeenCalledWith('large');
// we also expect, that the logic of your setter method works correctly: `this.size = !value ? 25 : this.size;`
// since we pass value, your `this.size` will not change
expect(component.size).toBe(10);
});
编辑
这是另一个测试,以防我们将setter参数传递给空字符串:
it('call small setter method 2', () => {
const small = spyOnProperty(component, 'small', 'set').and.callThrough();
component.small = '';
expect(small).toHaveBeenCalledWith('');
expect(component.size).toBe(25);
});
正如预期的那样 - small
setter将被称为''空字符串,而size
属性将是25因为:this.size = !value ? 25 : this.size;