【问题标题】:How do you test a function which is called with a constant using jasmine + TypeScript如何测试使用 jasmine + TypeScript 使用常量调用的函数
【发布时间】:2016-11-29 15:39:35
【问题描述】:

我正在开发一个 Angular2 / TypeScript 项目并使用 jasmine 进行单元测试。

如何测试使用 jasmine 以常量调用的函数。 例如。 Logo.ts

export const RADIUS: number = 10;

export class Logo {
  ...
  protected drawCircle( x: number, y: number, r: number ){...}

  protected drawLogo(){
    this.drawCircle( RADIUS, RADIUS, RADIUS );
  }
  ...
}

Logo.spec.ts

describe('drawLogo', function () {
  beforeEach(() => {
    spyOn( logo, 'drawCircle');
  }
  it('should call drawCircle method with parameters'){
    expect( logo.drawCircle ).toHaveBeenCalledWith( 10, 10, 10 ); //This fails
  }
}

除了将常量作为参数传递给 toHaveBeenCalledWith 方法之外,还有其他测试方法吗?

【问题讨论】:

  • 您可以使用logo.drawCircle.calls.mostRecent().args 获得更多灵活性。
  • 你永远不会在你的测试中调用 drawLogo() 。那应该如何工作呢??

标签: javascript angularjs unit-testing typescript jasmine


【解决方案1】:

你需要先使用间谍

spyOn('logo','drawCircle');
logo.drawLogo();
 expect( logo.drawCircle ).toHaveBeenCalledWith( 10, 10, 10 );

【讨论】:

  • @tymspy 那么,解决方案是什么?因为你在刚刚发布的代码中做了同样的事情
  • @iberbeu 我错过了调用你提到的方法。
【解决方案2】:

将 RADIUS 导入您的规范文件,然后

expect( logo.drawCircle ).toHaveBeenCalledWith( RADIUS, RADIUS, RADIUS );

【讨论】:

    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    相关资源
    最近更新 更多