【问题标题】:Jasmine spying on method that calls external method (Angular 2)Jasmine 监视调用外部方法的方法(Angular 2)
【发布时间】:2017-08-15 11:24:46
【问题描述】:

在我的 Angular 2 应用程序中,如何测试我的 main 方法中的外部方法(依赖项)是否被相应地调用。

例如,

Class ServiceA
{
  constructor(
    private serviceB : ServiceB
  ){}


  //How do I test this method to make sure it does what it should ?
  mainMethod()
  {
    //External method
    this.serviceB.otherMethod();

    this.sideMethod();
  }

  sideMethod()
  {
    //Do something
  }
}

Class ServiceB
{
  constructor(){}

  otherMethod()
  {
    //Do something
  }
}

这是我目前尝试过的

it('On otherMethod returns false, do something', 
  inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
    spyOn(serviceB, 'otherMethod').and.returnValue(false);
    spyOn(serviceA, 'sideMethod');
    spyOn(serviceA, 'mainMethod').and.callThrough();


    expect(serviceB.otherMethod()).toHaveBeenCalled();
    expect(serviceA.sideMethod()).toHaveBeenCalled();
    expect(serviceA.mainMethod()).toHaveBeenCalled();
  }));

从上面的代码,我得到一个错误说明

无法为 otherMethod() 找到要监视的对象

这里有什么问题?

【问题讨论】:

    标签: unit-testing angular typescript jasmine


    【解决方案1】:

    您必须传递您的间谍serviceB.otherMethod 的函数引用。您当前正在通过调用serviceB.otherMethod() 调用间谍,这将返回otherMethod 的返回值而不是间谍。

    it('On otherMethod returns false, do something', 
        inject([ServiceA, ServiceB], (serviceA: ServiceA, serviceB: ServiceB) => {
        spyOn(serviceB, 'otherMethod').and.returnValue(false);
        spyOn(serviceA, 'sideMethod');
        spyOn(serviceA, 'mainMethod').and.callThrough();
    
        // Notice spy reference here instead of calling it.
        expect(serviceB.otherMethod).toHaveBeenCalled();
        expect(serviceA.sideMethod).toHaveBeenCalled();
        expect(serviceA.mainMethod).toHaveBeenCalled();
    }));
    

    Jasmine 文档:https://jasmine.github.io/2.0/introduction.html#section-Spies

    【讨论】:

    • 我在发布这个问题几分钟后就明白了,无论如何,谢谢!
    猜你喜欢
    • 2013-08-31
    • 2014-01-25
    • 2019-03-31
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多