我如何使用 Jasmine 监视从一个 class 调用的方法,这些方法存在于另一个 class 中?

How do I spy on methods called from one class that exist in another class using Jasmine?

我有办法

thisSvc.asyncOperation: function(id) {
   return thatSvc.getById(id);

是否可以创建一个间谍来告诉我 thatSvc.getById 是否已被调用,或者此设计是否为反模式?据我所知,只能在单个对象上创建间谍。

来自http://www.htmlgoodies.com/html5/javascript/spy-on-javascript-methods-using-the-jasmine-testing-framework.html#fbid=ib4OX6qA3oS

"spyOn() can only be used when the method already exists on the object. For simple tests, this is your best bet."

你可以监视任何你想要的东西,在你的茉莉花测试中,只要确保你得到了那个服务:

var thisSvc, thatSvc;

beforeEach(inject(function(_thisSvc_, _thatSvc_){
    thisSvc = _thisSvc_;
    thatSvc = _thatSvc_;
});

it('.asyncOperation should call thatSvc.getById', function(){
    spyOn(thatSvc, 'getById');
    var id = 4;

    thisSvc.asyncOperation(id);

    expect(thatSvc.getById).toHaveBeenCalledWith(id);
})