0

アプリのすべてが正常に機能するため、構文的に間違っているのは私のテストだけです。ここに私が取り組んでいるものの切り詰められたバージョンがあります。罪のない人々を保護するために、名前と場所が変更されました。

var m;

m = angular.module('CustomService', []);

window.CustomService = m.factory("CustomService", function($rootScope) {
  var sharedService;
  sharedService = {};
  sharedService.broadcastItem = function() {
    return console.log('Works!');
  };
  return sharedService;
});

window.MyCtrl = function($scope, $location, CustomService) {
  this.$inject = ['$scope', 'CustomService'];
  return $scope.test_method = function(date) {
    return CustomService.broadcastItem(date);
  };
};

describe('MyCtrl', function() {
  beforeEach(inject(function($rootScope, $controller, $location) {
    this.scope = $rootScope.$new;
    return this.controller = $controller(MyCtrl, {
      $scope: this.scope,
      $location: $location,
      CustomService: CustomService
    });
  }));
  return it('tests my method', function() {
    return this.scope.test_method('10-1984');
  });
});

そして、その最終行は次を返します:

TypeError: Object #<Object> has no method 'test_method'

変!私のアプリ全体が機能し、その方法が完璧に機能するという事実から繁栄しているからです. したがって、このモジュールを適切に注入していないに違いありません (推測!)。

4

2 に答える 2

3

コードとテストで多くのことが行われているため、すべてをリストするのは少し難しいです。(ログは別として) テスト対象の実装を提供していないため、このテストを完全に支援するのは難しいため、実行してテストしたいと思われるものをスタブ化しました。

だから、ここにテストがあります:

describe('MyCtrl', function() {

  var scope, controller;
  beforeEach(module('CustomService'));
  beforeEach(inject(function($rootScope, $controller, $location) {
    scope = $rootScope.$new();
    controller = $controller('MyCtrl', {
      $scope: scope
    });
  }));

  it('tests my method', function() {
    scope.test_method('10-1984');
    expect(scope.brodcastedValue).toEqual('10-1984');
  });
});

テストの問題は次のとおりです。

  • 不適切$new()なスコープの作成 ( はプロパティではなくメソッドです
  • モジュールへの参照の欠如:beforeEach(module('CustomService'));
  • コントローラーに指定された依存関係が多すぎます

テストに合格するようにコード自体も変更しました。

m.factory("CustomService", function($rootScope) {
  var sharedService;
  sharedService = {};
  sharedService.broadcastItem = function(date) {
    $rootScope.$broadcast('works', date);
  };
  return sharedService;
});

m.controller('MyCtrl', function($scope, $location, CustomService) {

  $scope.test_method = function(date) {
    CustomService.broadcastItem(date);
  };

  $scope.$on('works', function(event, date){
    $scope.brodcastedValue = date;
  });
});

上記があなたの意図であるかどうかはわかりません。とにかく、コードはCoffeScriptか何かから変換されたように見えるので(リターンとこれでいっぱいです)、私はそれが正しいかどうかわかりません。

最後に、機能するプランクです。これですべての詳細が明確になることを願っています: http://plnkr.co/edit/x2Jjvm8zwwaLZYV9aLfo?p=preview

于 2013-02-02T20:12:46.867 に答える
2

この行の構文に 1 つの誤りがあることに気付きました。

this.scope = $rootScope.$new;

新しいスコープを作成する代わりに、$rootScope の $new 関数を参照しています。これを試して:

this.scope = $rootScope.$new();
于 2013-02-02T20:03:06.627 に答える