可以从单元测试中看到在方法内部定义的变量

时间:2019-04-12 11:05:09

标签: angular unit-testing jasmine

我正在按角度运行单元测试,我可以测试是否调用了该方法,还可以查看是否定义了在该方法内部初始化的变量。请让我知道何时调用该方法,它还必须在其中定义变量

spec.ts

let spyDate = spyOn(component, "setDateFilter");
component.setDateFilter('2019', '2', '13', '2019', '3', '11');
expect(spyDate).toHaveBeenCalled();//passes
expect(component.filter.from).toBeDefined();//passes,but
console.log(component.filter.from);// is just ' ',I expect 2019-03-11T23:00:00.000Z
filter={
from:'',
to:''
}

component.ts

setDateFilter(yearX, monthX, dayX, yearY, monthY, dayY) {
  console.log(monthX + '  ' + monthY);
  //+''+ monthX+'' +dayX+''+ yearY+''+monthY+''+dayY );
  this.filter.from = (new Date(yearX, monthX, dayX, 0, 0, 0)).toISOString();
  this.filter.to = (new Date(yearY, monthY, dayY, 23, 59, 59)).toISOString();
}

1 个答案:

答案 0 :(得分:1)

您需要在调用spyOn()之后使用andCallThrough()。这样,间谍会将对它的所有调用传递给原始函数。

let spyDate=spyOn(component,"setDateFilter").andCallThrough();