gpt4 book ai didi

angularjs - Angular 单元测试未知提供商 : $scopeProvider

转载 作者:行者123 更新时间:2023-12-03 03:43:58 26 4
gpt4 key购买 nike

您好,我正在使用 Jasmine 编写第一个 Angular 测试,但我不断收到错误

------ 测试开始:文件: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;
}
]);

最佳答案

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

您需要在使用 $controller 提供程序实例化 Controller 时提供作用域。您可以在setUp中注入(inject)$rootScope,并且可以通过执行$rootScope.$new()来获取子作用域。将其作为参数注入(inject)到 $controller 构造函数中。即 $controller("MainCtrl", {$scope: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
}));

关于angularjs - Angular 单元测试未知提供商 : $scopeProvider,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com