测试角服务的内部方法调用测试、方法

2023-09-13 04:12:57 作者:谁都不可能成为珴旳全部了

我有以下简单的服务

app.factory('Shoes', function() {
    function a() {return 12;}
    function b() {return a();}

    return {
      a: a,
      b: b
    }
  })

我想测试如果方法 A,当我打电话的方法 B 被调用。我的测试是这样的:

I want to test if the method a is being called when I call method b. My test looks like this:

describe('Testing a Shoes service', function() {
  var service;

  beforeEach(module('plunker'));

  beforeEach(inject(function(Shoes) {
    service = Shoes;
  }))

  it('.b should call .a', function() {
    spyOn(service, 'a');
    service.b();
    expect(service.a).toHaveBeenCalled();
  })

});

但是测试失败。相关plunker是这里。

问题是我怎么可以测试这种相互作用的?

推荐答案

在这里会发生什么事是你对间谍 service.a 方法来设置,但内部 A (这是由内部称为b )仍然是相同的内部方法(即不是间谍),这就是为什么你测试失败。

What happens here is that you set on a spy on service.a method, but the internal a (which is called internally by b) is still the same internal method (i.e not the spy), that's why your test fail.

如果你真的想这样做,唯一的办法就是不调用内部 A ,但你的服务的方法:

If you really want to do that, the only way is to not call the internal a but the method of your service:

app.factory('Shoes', function() {
    return {
        a: function a() {
            return 12;
        },

        b: function b() {
            return this.a();
        }
    };
});

下面是你plunkr的更新: https://plnkr.co/edit/6FZptdcX9qwyOE6kbgAX

Here is an update of your plunkr: https://plnkr.co/edit/6FZptdcX9qwyOE6kbgAX

编辑:

只是一些解释: service.a 方法只是一个指向内部 A 方法。当你说 spyOn(服务'一'),你只是覆盖 service.a 指针指向一个完全不同的方法(即由茉莉创建的间谍)。内部 A 方法是私有的,将永远不会更新,因此,如果调用 A()在内部 b 方法,你只需要调用原始方法 A 不是 service.a 。

Just some explanation: the service.a method is just a pointer to the internal a method. When you say spyOn(service, 'a'), you are just overwriting the service.a pointer to point to a completely different method (i.e a spy created by jasmine). The internal a method is private and will be never updated, so if you call a() in your internal b method, you just call the original method a not the spy pointed by service.a.