【发布时间】:2016-02-01 15:02:30
【问题描述】:
作为 JS 单元测试和 Angular 测试的新手,我尝试使用 Jasmine 和 Karma 编写自己的测试。在多次尝试编写自己的测试失败后,我决定退后一步检查一切是否正常,所以我将示例控制器及其测试从Angular Documentation on Unit testing 复制到我的项目中,我什至无法让它工作..我觉得自己像个彻头彻尾的白痴,甚至无法让复制粘贴的代码工作..
这是我在step1Ctrl.js 文件中初始化的控制器:
模块在另一个文件中初始化。
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';
} }; });
这是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');
});
});
});
从文档中直接复制粘贴。
所以我在运行测试时遇到的错误是:
TypeError: undefined is not a constructor (evaluating '$controller('PasswordController', { $scope: $scope })')
这告诉我第二个beforeEach 中的$controller 函数失败了,因为$controller 未定义。所以看起来第一个beforeEach 没有运行,或者它运行了,但是inject 函数注入了一个未定义的值。
我也在使用browserify,如果这很重要的话。
这是我的karma.conf.js,如果这也有帮助的话:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js',
'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.1/angular-mocks.js',
'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
});
};
【问题讨论】:
标签: javascript angularjs unit-testing browserify karma-jasmine