【问题标题】:Write a unit test for service : AngularJS为服务编写单元测试:AngularJS
【发布时间】:2018-05-31 08:49:03
【问题描述】:

对于使用 jasmine 作为框架和 karma 作为测试运行程序的服务编写适当的单元测试,我几乎没有问题。

这是我在 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_;
  }));

我已经导入了angular-mocks.jsexample-service.js

当我尝试这种情况时,控制台会抛出 Error: [$injector:unpr] Unknown provider: $resourceProvider <- $resource <- myExampleService 错误。

请帮我解决这个问题。

【问题讨论】:

  • 请用实际的错误消息更新问题,因为它被截断了。即使答案解决了您的问题,这也可能对未来的读者有所帮助。
  • @estus 更新了问题:)

标签: javascript angularjs unit-testing ecmascript-6 karma-jasmine


【解决方案1】:

$resource 需要加载 angular-resource.js 和相应的模块:

  beforeEach(() => {
    angular
      .module('exampleApp', ['ngResource'])
      .service(ExampleService.selector, ExampleService);
    angular.mock.module('exampleApp');
  });

【讨论】:

  • 感谢您添加 ngResource 并导入 angular-resource.js 将解决这个问题,非常感谢@estus :)
  • 很高兴它有帮助。
  • 我能知道我们是否另外将 $urlMatcherFactory 传递给构造函数需要进行哪些更改?
  • 取决于 $urlMatcherFactory 是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多