gpt4 book ai didi

node.js - Angularjs 单元测试错误

转载 作者:行者123 更新时间:2023-11-28 21:11:54 25 4
gpt4 key购买 nike

我是编写单元测试的新手。我正在尝试简单的事情,在 Controller $scope.practicesaveInfo 函数中应该包含一个值。

我正在使用 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 初始化为一个空对象,它不会在任何地方被操作。这就是您的测试失败的原因。

你应该做什么:

  1. 使用虚拟 $scope 初始化您的 Controller
  2. 在每个测试中调用您的每个 Controller 方法
  3. 在每个测试中做你的断言

例如:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com