Angular Unit Test Unknown provider: $scopeProvider

前端 未结 2 1822
忘了有多久
忘了有多久 2020-12-10 15:53

Hello I am writing my first angular test with Jasmine but I keep getting the error

------ Test started: File: C:\\Users\\Regan\\Documents\\Visual Studio 2013\\WebSit

相关标签:
2条回答
  • 2020-12-10 16:09

    You haven't defined scope anywhere to pass into the controller

    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);
        }));
    
        var scope; //<--- define scope
        beforeEach(inject(function ($controller, $rootScope) {
            scope = $rootScope.$new(); //<--- initialize scope
            ctrl = $controller("MainCtrl", {$scope: scope}); //<--- inject scope
    
        }));
    
        it("should have lables", function () {
            expect(scope.labels).toBeDefined();
        });
    });
    
    0 讨论(0)
  • 2020-12-10 16:11

    Since there is no $scope service, $controller provider cannot instantiate the injected $scope argument.

    You need to provide the scope while instantiating a controller using the $controller provider. You can inject $rootScope in your setUp and you can get a child scope by doing $rootScope.$new(). Inject it as an argument to the $controller contstructor. i.e $controller("MainCtrl", {$scope:scope }) where scope is the new child scope of even you can pass in the $rootScope.

    i.e

       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
        }));
    
    0 讨论(0)
提交回复
热议问题