【问题标题】:AngularJS Form Unit Testing IssueAngularJS 表单单元测试问题
【发布时间】:2015-12-09 22:34:12
【问题描述】:

我正在尝试为我的表单处理控制器设置一个单元测试,但我似乎在正确设置它时遇到了问题。

这是我的控制器处理表单的代码:

app.controller("FormController", ['$scope', '$http', '$window',  function($scope, $http, $window) {
    $scope.message = "";

    $scope.processForm = function() {
     $scope.message = "Processing form";
     $scope.messageStyle = {
     "color": "green"
     };

     $http({
        method: 'POST',
        url: '/register',
        data:{
          "username": $scope.user.username,
          "email": $scope.user.email,
          "password": $scope.user.password,
          "confirm": $scope.user.confirm
        }
      }).success(function(data) {
        $scope.message = data.msg;

        if (data.success) {
          $window.location.href = "/confirm";
        } else {
          $scope.messageStyle = {
            "color": "red"
          };
        }

      });

    };
   }]);

这是我使用 Mocha 和 Chai 的单元测试代码:

describe("FormController", function(){

  var scope;
  var ctrl;
  var httpBackend;
  var http;

   beforeEach(module("home"));

   beforeEach(inject(function($rootScope, $controller, $httpBackend, $http) {

     scope = $rootScope.$new();
     http = $http;
     ctrl = $controller("FormController", {$scope : scope, $http : http});
     httpBackend = $httpBackend;
   }));

  describe("when calling the processForm function", function(){

  beforeEach(function() {
       scope.processForm();

    });

    it("Should contain a message", function(){
      expect(scope.message).to.equal("Processing form");
    });

   });

});

当我运行测试时,我得到以下错误:TypeError: 'undefined' is not an object (evaluating '$scope.user.username')

我应该如何解决这个问题?

【问题讨论】:

  • 为什么要对 POST 数据进行字符串化并添加内容类型标头? Angular 的 $http 为您完成所有这些工作
  • 另外,你显然需要在调用processForm之前在你的作用域上创建一个user对象
  • @Phil 我已更新我的代码以反映 POST 数据更改。我的 user 来自 ng-model。所以我在 html 表单中有类似 ng-model="user.username" 的东西。
  • 控制器测试不包含任何模板,因此您必须在调用processForm()之前手动设置模型数据
  • 在测试中调用scope.processForm() 之前,请添加scope.user = {username: 'foo', email: 'foo@example.com', ...}。当然,您还必须将预期的 HTTP 调用添加到 httpBackend

标签: javascript angularjs unit-testing mocha.js chai


【解决方案1】:

在每个之前尝试以下代码

 beforeEach(function() {
   elm = angular.element(
       '<form ng-controller="FormController">' +
    '<input ng-model="user.username">' +
         '<input ng-model="user.email">' +
         '<input mg-model="user.password">' +
         '<input mg-model="user.confirm">' +
        '</form>');
     scope = $rootScope;
     $compile(elm)(scope);
     scope.$digest();
        scope.processForm();

 });

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2014-08-06
    • 1970-01-01
    • 2012-12-01
    • 2013-05-27
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    相关资源
    最近更新 更多