【问题标题】:Mocking a service in jasmine: missing provider在茉莉花中模拟服务:缺少提供者
【发布时间】:2015-12-03 21:58:23
【问题描述】:

我对单元测试很陌生。我正在编写代码。我的 js 文件有:

app.service("appService", function($http) {
  this.getData = function(url) {
    return $http.get(url);
  }

  this.foo = function() {
    console.log("Hello foo function");
  }
})

app.controller("productsController", ['$scope', '$http', 'appService',
  function($scope, $http, appService) {
    var pct = this;
    console.log("This is products controller");
    pct.url = "http://mysafeinfo.com/api/data?list=englishmonarchs&format=json";
    var jsonDataPromise = appService.getData(pct.url);
    jsonDataPromise
      .then(function(response) {
        pct.jsonData = response.data;
      }, function(err) {
        console.log("Error is: " + error);
      });
  }
]);

我正在使用 jasmine 框架在 karma.js 中对其进行单元测试。我已将 testfile.js 设为:

describe('unitTesting', function() {
  var $prodScope, prodCtrl, mockService;
  beforeEach(module('sampleApp')); //Name of angular module 
  var jsonData = {
    "name": "test_name",
    "email": "test_email"
  };

  beforeEach(function() {
    mockService = jasmine.createSpyObj('appService', ['getData', 'foo']);
  })

  beforeEach(inject(function($controller, $rootScope, $httpBackend, $http, $q, mockService) {
    defer = $q.defer();
    $prodScope = $rootScope.$new();
    prodCtrl = $controller('productsController', {
      $scope: $prodScope,
      $http: $http,
      appService: mockService
    });

    spyOn(mockService, "getData").and.callFake(function() {
      return defer.promise;
    });
    spyOn(mockService, "foo");

  }));

  //Here unit tests go

})

我的问题是,当我使用 karma start 运行测试时(我有 karma.conf.js),我收到错误:

[$injector:unpr]未知提供者:mockServiceProvider

谁能向我解释为什么我会收到这个错误?请解释正确的代码应该是什么。

【问题讨论】:

    标签: javascript angularjs node.js unit-testing


    【解决方案1】:

    您正在使用inject() 注入内部使用 Angular DI 系统的服务。对于这个用例,它正在 Angular 的 DI 系统中查找一个不存在的 mockService。

    要么从 inject() 参数中删除 mockService 并从它当前所在的 describe 范围中使用它,或者使用提供者 $provide 服务来提供 mockService 如果需要测试的东西。例如

    beforeEach(module(function($provide) {
      $provide.service('mockService', mockService); // where mockService is a constructor function
    }));
    

    More info

    【讨论】:

    • 这个链接真的很有用。还是谢谢。
    【解决方案2】:

    这是因为您试图在 beforeEach 注入中注入 mockService

    来自

      beforeEach(inject(function(
        $controller, 
        $rootScope, 
        $httpBackend, 
        $http, 
        $q, 
        mockService // REMOVE THIS!
      ) {
      // ....
      }));
    

      beforeEach(inject(function(
        $controller, 
        $rootScope, 
        $httpBackend, 
        $http, 
        $q
      ) {
      // ....
      }));
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多