Being new to JS unit testing and Angular testing in particular, I tried writing my own tests with Jasmine and Karma. After numerous failed attempts at writing my own tests, I decided to step back and check whether everything is working properly, so I copied the example controller and its tests from the Angular Documentation on Unit testing into my project and I am unable to get even that to work.. I feel like a complete idiot that can't even get the copy-pasted code to work..
So here is the controller that I have initialized in the step1Ctrl.js
file:
Module is initialized in another file.
var mainApp = angular.module("mainApp");
mainApp.controller('PasswordController', function PasswordController($scope) { $scope.password = ''; $scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
} }; });
And here's are the tests that live inside step1Ctrl.spec.js
:
describe('PasswordController', function() {
beforeEach(module('mainApp'));
var $controller;
beforeEach(inject(function(_$controller_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$controller = _$controller_;
}));
describe('$scope.grade', function() {
var $scope, controller;
beforeEach(function() {
$scope = {};
controller = $controller('PasswordController', { $scope: $scope });
});
it('sets the strength to "strong" if the password length is >8 chars', function() {
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
it('sets the strength to "weak" if the password length <3 chars', function() {
$scope.password = 'a';
$scope.grade();
expect($scope.strength).toEqual('weak');
});
});
});
Literally copy-pasted from the documentation.
So the error that I get upon running the tests is:
TypeError: undefined is not a constructor (evaluating '$controller('PasswordController', { $scope: $scope })')
Which tells me that the $controller
function in the second beforeEach
is failing, as $controller
is undefined. So it looks like the first beforeEach
doesn't run, or it does but an undefined value gets injected with the inject
function.
I am also using browserify
, if that matters.
Here is my karma.conf.js
, if that helps, as well:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'http://ift.tt/1KSqWqC',
'http://ift.tt/1NgogVP',
'http://ift.tt/1KSqU1W',
'test/unit/**/*.js'
],
exclude: [
],
preprocessors: {
'app/main.js': ['browserify']
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['PhantomJS'],
browserify: {
debug: true,
transform: []
},
plugins: [
'karma-phantomjs-launcher', 'karma-jasmine', 'karma-bro'
],
singleRun: false,
concurrency: Infinity
});
};
Aucun commentaire:
Enregistrer un commentaire