单元测试中的错误有助于我解决这个问题

时间:2014-12-29 09:08:10

标签: angularjs unit-testing angular-ui karma-jasmine

我在这个测试中遇到了错误。谁能告诉我为什么会这样呢?

describe('Controller: LoginCtrl', function () {
  beforeEach(function(){

    var $httpBackend;
    module("loginModule");
  });

  beforeEach(inject(function($controller, $rootScope, $location, $auth, $httpBackend) {
    this.$location= $location;
    this.$httpBackend=$httpBackend;
    this.scope= $rootscope.$new();
    this.redirect = spyOn($location,'path');

    $controller('LoginCtrl',{
        $scope: this.scope,
        $location: $location,
        auth: $auth

    });

  }));



  describe("succesfully loggin in",function(){
    it("should redirect you to home",function(){
        //arrange
        $httpBackend.expectPOST('/login',scope.login).respond(200);
        //act
        scope.login();
        $httpBackend.flush();

        //assertion
        expect(this.redirect).toHaveBeenCalledWith('/login');
    });

  });
});

我得到的错误是:

Error: [$injector:unpr] Unknown provider: $authProvider <- $auth
http://errors.angularjs.org/1.2.28/$injector/unpr?p0=%24authProvider%20%3C-%20%24auth
    at C:/xampp/htdocs/app/bower_components/angular/angular.js:3801
    at getService (C:/xampp/app/bower_components/angular/angular.js:3929)
    at C:/xampp/htdocs/app/bower_components/angular/angular.js:3806
    at getService (C:/xampp/htdocs/app/bower_components/angular/angular.js:3929)
    at invoke (C:/xampp/htdocs/app/bower_components/angular/angular.js:3956)
    at workFn (C:/xampp/htdocs/app/bower_components/angular-mocks/angular-mocks.js:2177)
undefined
ReferenceError: Can't find variable: $httpBackend
    at C:/xampp/htdocs/test/spec/controllers/login.js:32
PhantomJS 1.9.8 (Windows 8): Executed 1 of 1 (1 FAILED) ERROR (0.02 secs / 0.021 secs)
Warning: Task "karma:unit" failed. Use --force to continue.

1 个答案:

答案 0 :(得分:1)

Angular为许多内容($controller$httpBackend)提供自动模拟,但不为$auth提供。您需要实施自己的$authProvider(请参阅https://docs.angularjs.org/guide/providers以获取一般概述)或直接模拟$auth

Use $provide让Angular了解您的新自定义模拟。

相关:Injecting a mock into an AngularJS service