Reputation: 3218
I have a project with AngularJS + RequireJS + Karma + Jasmine.
My project structure follows:
lib
--angular.js
--angular-mocks.js
--require.js
node_modules
--(...)
test
--test-main.js
--spec
--firstTest-spec.js
web
--js
--require_config.js
--controllers
--MainController.js
--modules
--AppModule.js
index.html
karma.conf.js
In my test file, I have the following code:
define(['angularMocks', 'modules/AppModule'],
function(angularMocks, AppModule) {
describe("my test suite", function() {
var scope;
beforeEach(module('AppModule'));
it('testing for a controller', inject(function($rootScope, $controller) {
var scope = $rootScope.$new();
var ctrl = $controller('MainController', {
$scope : scope
});
console.log("The test is running ->" + ctrl);
}));
});
});
And with this it works, because I'm using the AppModule
dependency. The thing is that I want to just test the Controller
, and the Controller
itself is independent. So I tried something like this:
define(['angularMocks', 'controllers/MainController']
But if I try to access the Controller
like this I can't get it to work.
Since I couldn't find my question answered elsewhere, I ask, do I have to always reference the Module
of the Controller
I'm testing or can I test my Controller
with no Module
reference?
Upvotes: 0
Views: 678
Reputation: 1117
A controller cannot only be defined within the context of a module, so you will need to have some module defined in order to test the controller.
If you want to be able to isolate testing of the controller without pulling in other parts of the main application module, you could put the controller in a module of its own:
// MainController.js:
define([],
function() {
return angular.module('mainController', []).
controller('MainController', /* ... */);
});
// AppModule.js:
define(['controllers/MainController'],
function(mainControllerModule) {
return angular.module('AppModule', [mainControllerModule.name]);
});
Alternatively (possibly depending on your philosophy on how modules should be organized), if you just want to hide the fact that the controller is dependent on the app module from the test file, you could use an approach like:
// MainController.js:
define(['modules/AppModule'],
function(AppModule) {
return angular.module(AppModule.name).
controller('MainController', /* ... */);
});
// AppModule.js:
define([],
function() {
return angular.module('AppModule', []);
});
// firstTest-spec.js:
define(['angularMocks', 'controllers/MainController'],
function(angularMocks, MainControllerModule) {
// ...
beforeEach(module(MainControllerModule.name));
});
Upvotes: 1