AngularJS服务单元测试报错:$resourceProvider未知提供者求助
AngularJS服务单元测试中$resource依赖注入错误的解决办法
我之前用Jasmine做测试框架、Karma做运行器写AngularJS服务单元测试时,也碰到过一模一样的[$injector:unpr]错误,这就来帮你解决。
先看你的服务实现代码(example-service.js):
export default class ExampleService { constructor($resource, $http) { 'ngInject'; this.$resource = $resource; this.$http = $http; } exampleMethodOne() { //some code lines } exampleMethodTwo() { //some code lines } } ExampleService.selector = 'myExampleService';
你的测试代码(example-service.test.js):
let myExampleService, $httpBackend; beforeEach(() => { angular .module('exampleApp', []) .service(ExampleService.selector, ExampleService); angular.mock.module('exampleApp'); }); beforeEach(inject((_myExampleService_, _$httpBackend_) => { myExampleService = _myExampleService_; $httpBackend = _$httpBackend_; }));
错误原因分析
控制台抛出的Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource <- myExampleService,核心问题是:
$resource并不是AngularJS核心模块自带的服务,它属于ngResource模块提供的功能- 你在测试中创建的
exampleApp模块没有依赖ngResource,所以Angular的注入器找不到$resource的提供者,自然无法实例化依赖它的myExampleService
解决步骤
只需要修改测试代码中的模块定义,把ngResource加入到exampleApp的依赖数组里即可:
修改后的测试代码:
let myExampleService, $httpBackend; beforeEach(() => { angular // 这里添加ngResource到依赖数组中 .module('exampleApp', ['ngResource']) .service(ExampleService.selector, ExampleService); angular.mock.module('exampleApp'); }); beforeEach(inject((_myExampleService_, _$httpBackend_) => { myExampleService = _myExampleService_; $httpBackend = _$httpBackend_; }));
额外注意事项
- 确保你的测试环境中已经引入了
angular-resource.js文件(和angular.js、angular-mocks.js一起引入),否则即使添加了模块依赖,还是会找不到相关定义。
内容的提问来源于stack exchange,提问作者John Singh
相关产品推荐
相关产品推荐

