我是编写单元测试的新手。我正在尝试简单的事情,在 Controller $scope.practice
的 saveInfo
函数中应该包含一个值。
我正在使用 webstorm 来运行我的测试。我想检查是否定义了 $scope.practice 的 saveInfo
函数。
测试/练习.js
'use strict';
describe('myApp', function() {
describe('Controller: PracticeCtrl', function () {
var $http, $scope, $routeParams, $location, $locale, $timeout;
// load the controller's module
beforeEach(function () {
// Load the controller's module
module('myApp');
inject(function ($controller, $rootScope) {
$scope = {};
});
});
it('should define a practice property', function () {
expect($scope.practice).toBeDefined();
});
});
});
practice.js - Controller
angular.module('myApp').controller('PracticeCtrl', function ($http, $scope, $routeParams, $location, $locale, $timeout) {
$scope.saveInfo = function () {
$scope.practice = '52300099';
Practices.updateStampApproval().updateInfo($scope.practice);
};
$scope.updateInfo = function () {
....
}
$scope.getInfo = function () {
....
}
给我错误:-
Expected undefined to be defined.
Error: Expected undefined to be defined.
在我的 Controller 中定义了 $scope.practice
。那么为什么它显示错误。
如何明智地测试 function
意味着我如何编写测试,它只会检查 Controller 中的 1 个函数,例如“保存信息”?
最佳答案
您正在将 $scope
初始化为一个空对象,它不会在任何地方被操作。这就是您的测试失败的原因。
你应该做什么:
- 使用虚拟
$scope
初始化您的 Controller - 在每个测试中调用您的每个 Controller 方法
- 在每个测试中做你的断言
例如:
describe('myApp', function() {
describe('Controller: PracticeCtrl', function () {
var $http, $scope, $routeParams, $location, $locale, $timeout, practiceCtrl;
// load the controller's module
beforeEach(function () {
// Load the controller's module
module('myApp');
inject(function ($controller, $rootScope) {
$scope = $rootScope.$new();
practiceCtrl = $controller("PracticeCtrl", {
$scope: $scope
});
});
});
it('should define a practice property', function () {
$scope.saveInfo();
expect($scope.practice).toBeDefined();
});
});
});
我希望我已经足够清楚,可以帮助到您。
关于node.js - Angularjs 单元测试错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22377833/