【发布时间】:2017-03-28 20:03:45
【问题描述】:
我正在尝试测试控制器功能,但 Karma 无法按预期拾取它。我已按照以下指示:https://docs.angularjs.org/guide/controller
这是我的代码:
var app = angular.module('calApp', []);
app.controller('calCtrl', function($scope) {
$scope.sum = function(x, y) {
return x + y;
};
});
describe('calCtrl function', function() {
describe('calCtrl', function() {
var $scope;
beforeEach(module('calApp'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.new();
$controller('calCtrl', {$scope: $scope});
}));
it('should add 2 numbers correctly', function() {
expect($scope.sum(1, 2)).toBe(3);
});
it('should subtract 2 numbers correctly', function() {
expect($scope.subtract(5, 3)).toBe(2);
});
});
});
我希望测试为 $scope.sum() 提供 1 次通过,为 $scope.substract() 提供 1 次失败。请帮忙!
错误: TypeError: undefined is not an object (evalating '$scope.subtract') in tests/spec.js
还有: 已执行 2 次,共 2 次(2 次失败)
karma.conf.json:
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'lib/angular.js',
'lib/angular.min.js',
'lib/angular-mocks.js',
'public_html/*.html',
'public_html/*.js',
'tests/*.js'
],
// list of files to exclude
exclude: [
"**/angular-scenario.js"
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
更新:我也有一个 FAILED for expect(true).toBe(true)
【问题讨论】:
-
那么发生了什么?你遇到了什么错误?
-
对不起,我忘了补充。现在已经结束了。
-
我还注意到你有 angular.js 定义了两次'lib/angular.js'和'lib/angular.min.js',
-
我已经解决了这个问题。谢谢!我认为问题不在代码中,因为我也有一个 FAILED for expect(true).toBe(true)。
-
您的 beforeEach 可能会离开 $scope 而没有使用实际控制器进行装饰。关注code.angularjs.org/1.5.7/docs/guide/unit-testing