作为 JS 单元测试尤其是 Angular 测试的新手,我尝试使用 Jasmine 和 Karma 编写自己的测试。在多次尝试编写自己的测试失败后,我决定退后一步,检查是否一切正常,所以我从 Angular Documentation on Unit testing 复制了示例 Controller 及其测试。进入我的项目,我什至无法让它工作..我觉得自己像个彻头彻尾的白痴,甚至无法让复制粘贴的代码工作..
这是我在 step1Ctrl.js
文件中初始化的 Controller :
模块在另一个文件中初始化。
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)了 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
});
};
最佳答案
我终于设法找出问题所在。 PhantomJS 根本没有描述错误消息。显然,它未能实例化我的主 Angular 模块 mainApp
,因为我没有包含我的主模块所依赖的外部模块的一些源文件(如 ngAnimate
等) .).
所以我将我的测试浏览器从 PhantomJS
切换到 Chrome,它实际上给了我有意义的错误,这些错误很快就指向了正确的方向。
关于javascript - Angular Testing 示例失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133754/