Reputation: 1384
I am having trouble getting unit tests working for an Angular JS app using Jasmine and RequireJs. I have created a Plunker here
The problem I am having is around the creation of a module. If I include the setup for the Angular module in my controller, like so (see Controller.js in Plunker):
angular.module('catalogManagementApp', []);
then everything works fine. However, this module is created in another file, so this won’t work. So if I try and setup the module in my test using the Angular Mocks module function I get an error saying "No module: catalogManagementApp".
If you look at the ControllerTests.js file, this makes sense because RequireJS is loading the Controller before my call to Angular Mocks to create the module:
beforeEach(module('catalogManagementApp'));
However, I am not sure how to get this working. As you can see from the commented out code in the ControllerTests.js file I have tried moving the require call for the Controller to after the call to setup the module, but this causes the Jasmine test runner to fail and still the same no module error.
The running of Jasmine with RequireJs code was adapted from this
Upvotes: 3
Views: 1164
Reputation: 1346
I had loads of issues getting angular, mocking and require to play nice with jasmine. In the end the answer was obvious you need to boot jasmine up and ensure it's fed your specs. This is a cut down version of what I did, I hope it helps to get you on the right track.
/* this would be 'main'*/
require.config({
paths: {
'jasmine-boot': 'lib/jasmine/boot',
'jashtml': 'lib/jasmine/jasmine-html',
'jasmine': 'lib/jasmine/jasmine',
'angular': 'lib/angular',
'angular-mocks': 'lib/angular-mocks',
'app': 'src/app',
'test': 'spec/first.spec',
},
shim: {
'jashtml': {
deps: ['jasmine']
},
'jasmine-boot': {
deps: ['jasmine', 'jashtml']
},
'angular': {
exports: "angular"
},
'angular-mocks': {
exports: "angular.mock",
deps: ['angular']
},
'test': {
deps: ['angular-mocks']
}
}
});
require(['jasmine-boot'], function () {
require(['test'], function () {
//trigger Jasmine
window.onload();
});
});
/*this would be 'first.spec'*/
define(['app'], function (app) {
var mockScope, controller;
function init() {
return angular.mock.inject(function ($injector, _$rootScope_, _$controller_) {
mockScope = _$rootScope_.$new();
controller = _$controller_('testCtrl', {
$scope: mockScope
});
});
};
describe('expect require', function () {
beforeEach(module("app"));
beforeEach(init());
describe('to be ', function() {
it('clever', function () {
var foo = "bar";
controller.setValue(foo);
expect(controller.value).toBe(foo);
});
});
});
});
/*jasmine spec runner*/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.1.3</title>
<link rel="shortcut icon" type="image/png" href="jasmine_favicon.png">
<link rel="stylesheet" href="jasmine.css">
<script src="../../require.js" data-main="main.js"></script>
</head>
<body>
</body>
</html>
Upvotes: 1