如何测试使用 jasmine + TypeScript 使用常量调用的函数

Posted

技术标签:

【中文标题】如何测试使用 jasmine + TypeScript 使用常量调用的函数【英文标题】:How do you test a function which is called with a constant using 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() 。那应该如何工作呢?? 【参考方案1】:

你需要先使用间谍

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

【讨论】:

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

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

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

【讨论】:

以上是关于如何测试使用 jasmine + TypeScript 使用常量调用的函数的主要内容,如果未能解决你的问题,请参考以下文章