Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using the mock folder for karma test in yeoman angularjs

I have a angularjs application, which I generated with yeoman. In the karma.conf.js is a reference to test/mock/**/*.js. I have troubles to find out, how I use this folder. Currently I have a simple Service:

'use strict';

angular.module('tvcalApp')
  .factory('Series', function ($resource) {
    return $resource('/search/:search');
  });

and a Test

'use strict';

var $httpBackend;

describe('Service: Series', function () {

  // load the service's module
  beforeEach(module('tvcalApp'));

  // instantiate service
  var Series;
  beforeEach(inject(function (_Series_) {
    Series = _Series_;
  }));

  beforeEach(inject(function ($injector) {
      var url_get = '/search/The%20Simpsons';

      var response_get = [{"seriesid": "71663"}];

      $httpBackend = $injector.get('$httpBackend');

      $httpBackend.whenGET(url_get).respond(response_get);

  }));

  it('should return a list if search for The Simpsons', function () {
      var res = Series.query({search: 'The Simpsons'});
      $httpBackend.flush();
        expect(res[0].seriesid === 71663);
      });

});

This is working. But I wonder If I could use the mock folder from the karma.conf.js for the mocking function. Is it possible to move the mock part into the mock folder and use it for all unit test?

I could not find any example or documentation for this folder. Can someone please point me to to an example or documentation how to use the mock folder.

like image 299
Someone561 Avatar asked Sep 07 '13 14:09

Someone561


1 Answers

Basically i have done something like this looking at angular-mocks.js:
Let's say may app is called ql. and i have a loginService that i want to mock:

mocks/servicesMock.js looks like this:

'use strict';

var ql = {};
ql.mock = {};

ql.mock.$loginServiceMockProvider = function() {
  this.$get = function() {
    var $service = {
      login: function() { }
    };
    return $service;
  };
};

angular.module('qlMock', ['ng']).provider({
  $loginServiceMock: ql.mock.$loginServiceMockProvider
});

Then in my tests i can injeck $loginServiceMock:

'use strict';

describe('LoginController tests', function () {
  // load the controller's module
  beforeEach(module('ql'));
  // load our mocks module
  beforeEach(angular.mock.module('qlMock'));

  var loginController,
    loginServiceMock,
    scope;

  // Initialize the controller and a mock scope
  // $loginSericeMock will be injected from serviceMocks.js file
  beforeEach(inject(function ($controller, $rootScope, $loginServiceMock) {
    scope = $rootScope.$new();
    loginServiceMock =  $loginServiceMock;
    loginController = $controller('LoginController', {
      $scope: scope,
      loginService: loginServiceMock
    });
  }));
});
like image 175
gerasalus Avatar answered Sep 29 '22 08:09

gerasalus