Unit testing 如何使用jasmine为下面的TS函数编写单元测试用例

Unit testing 如何使用jasmine为下面的TS函数编写单元测试用例,unit-testing,angular7,Unit Testing,Angular7,我正在尝试为下面的函数编写单元测试(comparevalues)。但我无法模拟数据来涵盖分支机构。 TS: public排序更改(排序:SortDescriptor[]):void{ this.sort=排序; this.SelectedData.sort(this.compareValues(this.sort[0].field,this.sort[0].dir)); } 公共比较值(键:任意,顺序:任意){ 返回函数(a,b){ 如果(!a.hasOwnProperty(键)| |!b.ha

我正在尝试为下面的函数编写单元测试(comparevalues)。但我无法模拟数据来涵盖分支机构。 TS:

public排序更改(排序:SortDescriptor[]):void{
this.sort=排序;
this.SelectedData.sort(this.compareValues(this.sort[0].field,this.sort[0].dir));
}
公共比较值(键:任意,顺序:任意){
返回函数(a,b){
如果(!a.hasOwnProperty(键)| |!b.hasOwnProperty(键)){
//属性在两个对象上都不存在
返回0;
}
const varA=(一个[key]=“string”的类型)?
a[key].toUpperCase():a[key];
const varB=(b的类型[键]='string')?
b[key].toUpperCase():b[key];
让比较=0;
if(varA>varB){
比较=1;
}else if(varA

请帮助我为“comparevalues”函数中的'if',else'条件编写单元测试用例

,以便涵盖
if
else
,您需要模拟
中的值。从函数中选择数据与

我假设这是一个组件,因此您可以这样模拟
this。SelectedData

// add a spy for the property returning a xyz
const spy = spyOnProperty(component, 'SelectedData').and.returnValue([{ xyz: 23 }, { xyz: 44 }]);

// call the sortChange with the options looking for the key test that doesn't exist
component.sortChange([{ field: 'test', dir: 'asc' }])
要测试函数的返回,我们需要模拟它:

const spyFn = spyOn(component, 'compareValues').and.callThrough();

expect(spyFn.calls.first().returnValue).toEqual(0)
完整示例:

// add a spy for the property returning a xyz
const spy = spyOnProperty(component, 'SelectedData').and.returnValue([{ xyz: 23 }, { xyz: 44 }]);
const spyFn = spyOn(component, 'compareValues').and.callThrough();

// call the sortChange with the options looking for the key test that doesn't exist
component.sortChange([{ field: 'test', dir: 'asc' }])

expect(spyFn.calls.first().returnValue).toEqual(0)

然后,要测试其他分支,您只需以此示例为例,根据
if
else
s

中的条件正确应用,我已经尝试了上述解决方案。但我犯了这个错误。“错误:属性SelectedData没有访问类型get。”能否提供有关SelectedData的详细信息?组件。SelectedData=[{materialCode:'mat-01',materialDesc:'materialDesc',uomId:2,uomDesc:'uom desc',materialQty:'10',expDeliveryQty:'1',exDeliveryDate:'15-03-2012',isMatSelected:true,},{MATERALCODE:'mat-02',MATERALDESC:'MATERIASDESC',uomId:1,uomDesc:'uom asd',MATERALQTY:'10',EXPDERYQTY:'11',EXPDERYDATE:'15-03-2012',isMatSelected:true,}];如果在调用函数之前尝试直接更改变量,而不是像这样模拟它:
component.SelectedData=[{xyz:23},{xyz:44}]
或者如果是私有的
component['SelectedData']=[{xyz:23},{xyz:44}]
// add a spy for the property returning a xyz
const spy = spyOnProperty(component, 'SelectedData').and.returnValue([{ xyz: 23 }, { xyz: 44 }]);
const spyFn = spyOn(component, 'compareValues').and.callThrough();

// call the sortChange with the options looking for the key test that doesn't exist
component.sortChange([{ field: 'test', dir: 'asc' }])

expect(spyFn.calls.first().returnValue).toEqual(0)