javascript - 有人可以帮助解释如何用 Jasmine 测试这个 AngularJS 吗?

标签 javascript angularjs jasmine

所以我有一个简单的功能:

wpApp = angular.module('wpApp', ['ngRoute']);

wpApp.controller("ctrlr", function($scope) {
    $scope.message = 'This is the page';
});

我正在尝试使用具有以下规范的 Jasmine 来测试它:

describe("A suite", function() {
    var scope;
    beforeEach(inject(function($rootScope, $controller) {
        scope = $rootScope.$new();
        $controller("controller", {
            $scope: scope
        });
    }));

    it("should have the default message", function() {
        return expect(scope.message).toBe('This is the page');
    });
});

但是,它不起作用,因为实际值未定义。

我对 AngularJS 以及注入(inject)的想法都比较陌生。我一直在 StackOverflow、文档和教程中查找,但我似乎不太清楚我到底做错了什么。

希望这是一件小事。有人可以帮我看看我需要对我的规范进行哪些更改吗?

最佳答案

您需要加载您的模块:

beforeEach(module('wpApp'));

然后你需要加载正确的 Controller :

$controller("ctrlr", {
    $scope: scope
});

完整代码:

describe("A suite", function() {
  var scope;

  beforeEach(module('wpApp'));

  beforeEach(inject(function($rootScope, $controller) {
    scope = $rootScope.$new();
    $controller("ctrlr", {
      $scope: scope
    });
  }));

  it("should have the default message", function() {
    return expect(scope.message).toBe('This is the page');
  });
});

或者:

describe("A suite", function() {

  var $scope;

  beforeEach(function() {

    module('wpApp');

    inject(function($rootScope, $controller) {

      $scope = $rootScope.$new();

      $controller("ctrlr", {
        $scope: $scope
      });
    })
  });

  it("should have the default message", function() {
    return expect($scope.message).toBe('This is the page');
  });
});

关于javascript - 有人可以帮助解释如何用 Jasmine 测试这个 AngularJS 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24064000/

相关文章:

javascript - 在一个 ViewModel 中绑定(bind)多个 ObservableArrays 的 Knockout.js 最佳实践

javascript - 除了在开发期间进行测试之外,在登台服务器上进行测试还有哪些好处?

javascript - 10 $digest() 迭代在 IE 中达到错误。不知道为什么

javascript - 如何防止在解析完成之前更改路由?

javascript - 如何设置 Karma + Jasmine 以使用 ES6 模块

javascript - 类型错误 : Cannot read property 'args' when creating spy with Jasmine

javascript - 使用 javascript/coffeescript 的依赖注入(inject)以帮助可测试性

javascript - "JavaScript heap out of memory"传输大文件时

javascript - 如何在 VueJS 上允许请求 header 字段 access-control-allow-origin

javascript - 如何将 Ng-if 与 Firebase 结合使用