When should I use $provide versus Jasmine Spies in my Angular JS Unit tests

安稳与你 提交于 2019-12-03 02:54:08

From my own (limited) experience, I would say do whatever approach makes:

  • The test code simpler / clearer / shorter
  • Limits the assumptions about what the code your testing does internally.
  • Reduces its side-affects (like running actual Ajax requests)
  • Keeps the test as short as possible, in terms or run time.

Usually the spyOn approach works when, in order to do the above, I would like to stub a single method from a service / factory. If I need to mock an entire service / factory, then use $provide.

A few specific cases come to mind that require one or the other:

  • If you're testing a service, then to stub other methods from that service, you'll have to use spyOn

  • To ensure that extra dependencies aren't introduced later in the code under test, than $provide adds a bit more protection. Say, if you want to ensure that ServiceA only requires myMethod from ServiceB, then $provide I think would be the way to go, as if ServiceA calls any undefined methods from ServiceB during the test, errors would be raised.

    $provide.provider('ServiceB', {
        myMethod: function() {}
    });
    
  • If you want to mock a factory that returns a function, so:

    app.factory('myFactory', function() {
      return function(option) {
        // Do something here
      }
    });
    

    Which is used as:

    myFactory(option);
    

    Then to verify that some code calls myFactory(option) I think there is no alternative then to use $provide to mock the factory.

Just by the way, they're not mutually-exclusive options. You can use $provide and then still have spies involved. In the previous example, if you want to verify the factory was called with an option, you might have to:

var myFactorySpy = jasmine.createSpy();
$provide.provider('myFactory', myFactorySpy);

And then in the test at the appropriate point:

expect(myFactorySpy).toHaveBeenCalledWith(option);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!