0

I am trying to use AngularJS with RequireJS currently, but I do not know how to make the test work with injection. Without RequireJS we could,

Impl

PhoneListCtrl.$inject = ['$scope', '$http'];  
var PhoneListCtrl = ['$scope', '$http', function($scope, $http) { 
    /* constructor body */ 
}];  

Test

beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
  $httpBackend = _$httpBackend_;
  $httpBackend.expectGET('phones/phones.json').
      respond([{name: 'Nexus S'}, {name: 'Motorola DROID'}]);
  scope = $rootScope.$new();
  ctrl = $controller(PhoneListCtrl, {$scope: scope});
}));  

However, when we use RequireJS we may define the controller as following,

demoController.js

define(["dependency"], function() {
    /* constructor body */ 
});

When using this controller, we add it as one of the dependencies and do not have a variable declaration.(Let me just use "Controller" as an example since we'd better call it "Service")

someJS.js

define(["demoController"], function(controller) {
     controller.method();
});

My Question
How can we inject the $http, $scope(or something else) to the target controller or service for testing when using RequireJS(AMD)?

Any help would be highly appreciated.

2 Answers 2

1

I've done something similar:

/*global define, document */

define(['angular', 'jquery'], function (angular, $) {
    'use strict';

    return function () {
        var $injector = angular.bootstrap(document, ['myApp']);
        var $controller = $injector.get('$controller');
        var myController = $controller('myController');
    };
});

The idea is that angular.bootstrap returns an injector, which allows you to fetch a service.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer, but I still don't know how to implement it. I mean I want to inject $httpBackend for testing, in this case how to use your example?
Hmm, i tried it myself with a fiddle, and couldn't solve it. Actually, I wouldn't bother to use requirejs for unit/e2e testing. Consider using testacular however
0

I finally made it work by following.

angular.module('app').controller('MyController', ['$scope', 'dep2', function              ($scope, dep2) {
    $scope.method = function () {//do something};
}]);

We can use this controller in test cases like this:

inject(function($controller, $rootScope, dep2) {
        scope = $rootScope.$new();
        myController = $controller("MyController",
                {
                    $scope : scope,
                    dep2: dep2
                });
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.