Test AngularJS factory function with Jasmine

℡╲_俬逩灬. 提交于 2019-12-02 18:47:37
Caio Cunha

You're not too far from what you need. First off, as you require my_data as my_module dependency, you don't need to inject my_module to the controller, just the factory (my_factory);

Secondly, you want to make use of ngMock. The docs are not very complete, but give a good insight. More here and a example here (look for test/unit/controllers).

Basically, what you want to do is to mock the service so you can be assured it has been called. To achieve it, inject $provide to your angular.mock.module call and provide a mocked my_factory service. The best way to achieve it is something like this:

describe('testing my_controller.my_function', function () {
  var mockedFactory, $rootScope, $controller;

  beforeEach(module('my_module', function($provide) {
    mockedFactory = {
      save: jasmine.createSpy()
    };

    $provide.value('my_factory', mockedFactory);
  }));

  beforeEach(inject(function(_$rootScope_, _$controller_) {
    $rootScope = _$rootScope_;
    $controller = _$controller_;
  }));

  scope = $rootScope.$new();

  it('should call the save function', function() {
    scope.my_function();
    expect(mockedFactory.save).toHaveBeenCalled();
  });
}

This way you'll override my_factory dependency.

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