【问题标题】:How to spyOn a property called in a function?如何监视函数中调用的属性?
【发布时间】:2019-08-27 09:31:58
【问题描述】:

我需要监视“offsetWidth”,因为该值现在未定义。 getCurrentPage 是一个根据 id currentpage 获取元素的函数。

getCurrentPage 上的间谍可以工作,但我还需要声明 offsetWidth。但这没有用。

功能:

getCurrentPage() {
    return this.$document[0].getElementById('currentPage');
}

calculateStep() {
    this.stepWidth = this.getCurrentPage().offsetWidth / (this.totalSteps - 1);
    return this.stepWidth;
}

单元测试:

let stepWidth = new StepController();
stepWidth.totalSteps = 5;

const dummyCurrentPage = '<div id="currentPage" style="width: 20%;"></div>';

spyOn(stepWidth, 'getCurrentPage').and.returnValue(dummyCurrentPage);

const expectedResult = '200 / 4';

const result = stepWidth.calculateStep();

expect(result).toBe(expectedResult);
});

如何监视 this.getCurrentPage().offsetWidth 的 offsetWidth ?

【问题讨论】:

  • 变量dummyCurrentPage变成元素了吗?还是它仍然是一个字符串?
  • @DaniëlW.Crompton 它变成了一个字符串。

标签: javascript angularjs unit-testing jasmine karma-jasmine


【解决方案1】:

找到答案,将 dummyCurrentPage 转换为 angular.element 并将 offsetWidth 定义为 angular.element。

const element = angular.element('<div id="currentPage" style="width: 20%;"></div>');

stepWidth.getCurrentPage().offsetWidth = 50;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2020-07-16
    • 2016-01-13
    • 2015-05-13
    相关资源
    最近更新 更多