R
R
Roman Ogarkov2016-06-15 15:13:58
Angular
Roman Ogarkov, 2016-06-15 15:13:58

How to test with Jasmine in conjunction with Angular + RequireJS?

How to write tests using this application structure https://habrahabr.ru/post/225931/
Using karmaJS test runner and jasmineJS
Controller

define(['../module'], function (controllers) {
  'use strict';
  controllers.controller('topMenuCtrl', ['$scope','$http', function ($scope, $http) {
    $scope.list = [];
    $scope.get = function () {
      $http.get('../../../DB/options.json').success(function (response) {
        $scope.options = response;
        $scope.list = response;	
      });
    };
  }]);
});

Test
define([
  'angular',
  'app/app',
  'angularMocks'
], 
function (angular, app) {
  describe('app', function() {
    var scope, ctrl, httpBackend;

    beforeEach(module(app));

    beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
      httpBackend = _$httpBackend_;

      httpBackend.when('GET', '../../../DB/options.json').respond(['Hello world!']);

      scope = $rootScope.$new();

      ctrl = $controller('TopMenuCtrl', {
        $scope: scope
      });
    }));

    it('list', function() {
      expect(scope.list).toEqual([]);
    });
  });
});

Gives an error Error: [ng:areq] errors.angularjs.org/1.5.5/ng/areq?p0=TopMenuCtrl&... (line 23) Tell me
how to load modules using this code structure

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Ogarkov, 2016-06-15
@ogarich89

Figured it out myself =)

define([
  'angular',
  'app/app',
  'app/controllers/module',
  'angularMocks'
  ], 
  function (angular, app, controllers) {
    describe('app', function() {
      var scope, ctrl, httpBackend;

      beforeEach(module('app.controllers'));

      beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
        httpBackend = _$httpBackend_;

        httpBackend.when('GET', '../../../DB/options.json').respond(['Hello world!']);

        scope = $rootScope.$new();

        ctrl = $controller('topMenuCtrl', {
          $scope: scope
        });
      }));

      it('list', function() {
        expect(scope.list).toEqual([]);
      });
    });
  });

First, I blunted with the name of the controller, not TopMenuCtrl, a topMenuCtrl. Secondly, in addition to the app module, you also need to pass the controllers module. Then we turn to it like this
beforeEach(module('app.controllers'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question