一尘不染

角单元测试未知提供程序:$ scopeProvider

angularjs

您好,我正在用Jasmine编写我的第一个角度测试,但是我一直收到错误消息

------测试开始:文件:C:\ Users \ Regan \ Documents \ Visual Studio 2013 \ WebSites \
Regan \ testApp \ TestProject \ ng-tests \ MainCtrlSpec.js
------使用内联测试’MainCtrl模拟:应该有标签失败的错误:[$ injector:unpr]未知提供程序:$ scopeProvider <-$
scope <-MainCtrl

我尝试过玩,但是卡住了。如果您发现问题,请告诉我。如果还需要更多代码,请告诉我,但我认为问题出在这两个文件中。

MainCtrlSvc.js

/// <reference path="../../Scripts/angular/angular.js" />
/// <reference path="../../Scripts/angular/angular-mocks.js" />
/// <reference path="../../Scripts/chartjs/Chart.js" />
/// <reference path="../../Scripts/angular-chart.js-master/dist/angular-chart.js" />
/// <reference path="../../Scripts/controller/main-controller.js" />
/// <reference path="../../Scripts/service/data-service.js" />
/// <reference path="../../libs/jasmine/jasmine.js" />

describe("MainCtrl with inline mock", function () {
    beforeEach(module("ChartApp"));

    var ctrl, mockDataSrv;

    beforeEach(module(function($provide) {
        mockDataSrv = {
            labels: ["Reading", "Coding", "Thinking About Coding", "Reddit", "StackOverflow"],
            data: [500, 300, 300, 40, 220],
            type: "PolarArea",
            title: "Angular Chart Expriment"
        };
        $provide.value("DataSrv", mockDataSrv);
    }));

    beforeEach(inject(function ($controller) {
        ctrl = $controller("MainCtrl");
    }));

    it("should have lables", function () {
        expect(scope.labels).toBeDefined();
    });
});

MainCtrl.js

var app = angular.module("ChartApp", ["chart.js"]);

    app.controller("MainCtrl", ["$scope",
      function ($scope, DataSrv) {
          $scope.labels = DataSrv.labels;
          $scope.data = DataSrv.data;
          $scope.type = DataSrv.type;
          $scope.title = DataSrv.title;
      }
    ]);

阅读 184

收藏
2020-07-04

共1个答案

一尘不染

由于没有$scope服务,$controller提供程序无法实例化注入的$scope参数。

您需要在使用$controller提供程序实例化控制器时提供范围。您可以注入$rootScopesetUp,并通过执行操作获得子作用域$rootScope.$new()。将其作为参数传递给$controller构造方法。即$controller("MainCtrl", {$scope:scope }),范围是新的子范围,即使您可以传入$ rootScope。

   var ctrl, mockDataSrv, scope;
    //... Your code
    //...
    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new(); //get a childscope
        ctrl = $controller("MainCtrl", {$scope:scope }); //Pass it as argument as $scope's value
    }));
2020-07-04