AngualrJS with Karma - how do I write a unit test

2019-07-31 13:31发布

I am writing a simple AngularJS 1.x web app.

I have a module:

main.js:

var app = angular.module('app', []);

factory.js

app.factory('DataFactory', function(){

  var DataService = {};

  DataService.something = function() {
    return 5;
  };

  return DataService;

});

controller.js

app.controller('DataController', function ($scope, DataFactory) {
    $scope.searchText = null;
    $scope.results = DataFactory.something();
});

index.html:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</script>
    </head>
    <body ng-app="app" ng-controller="DataController">
        <script src="app.js"></script>
        <script src="factory.js"></script>
        <script src="controller.js"></script>
    </body>
</html>

test file:

  describe('Data Factory Test', function() {

    var Factory;

    beforeEach(function() {
      angular.module('app');
    });

    beforeEach(inject(function() {
      var $injector = angular.injector(['app']);
      Factory = $injector.get('DataFactory');
    }));

    it('is very true', function(){
        expect(Factory).toBeDefined();
      // var output = Factory.something();
      // expect(output).toEqual(5);
    });

  });

karma.conf.js:

frameworks: ['jasmine'],


// list of files / patterns to load in the browser
files: [
    'node_modules/angular/angular.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'app.js',
    'factory.js',
    'controller.js',
    'test/*.js'
]

How do I write a unit test to check if the factory exists, and to check the return of something?

I keep getting an error when i run karma start: Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $controllerProvider

Edit: I got it working. How would I write the unit test for the controller with and without a factory?

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-31 13:51

You need to call angular.injector:

'use strict';

(function() {
  describe('Factory Spec', function() {

    var Factory;

    beforeEach(function() {
      angular.module('app');
    });

    beforeEach(inject(function() {
      var $injector = angular.injector(['app']);
      Factory = $injector.get('DataFactory');
    }));

    it('is very true', function(){
      var output = Factory.something();
      expect(output).toEqual(5);
    });

  });
  }());

To test a controller:

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

From here;

查看更多
欢心
3楼-- · 2019-07-31 14:18

First part shows how service / factory can be tested. Second part show two ways of controller testing

  • we just expecting that some variables from $scope have been changed
  • we expect that some service / factory has been called

Probably all those kind of tests covers all our needs.

angular.module('app', []).factory('DataFactory', function() {

  var DataService = {};

  DataService.something = function() {
    return 5;
  };

  return DataService;

}).controller('DataController', function($scope, DataFactory) {
  $scope.searchText = null;
  $scope.results = DataFactory.something();
});

describe('Data Factory Test', function() {
  var Factory;

  beforeEach(module('app'));

  beforeEach(inject(function(_DataFactory_) {
    Factory = _DataFactory_
  }));

  it('is very true', function() {
    expect(Factory).toBeDefined();
    var output = Factory.something();
    expect(output).toEqual(5);
  });
});

describe('DataController ', function() {

  var $scope, instantiateController, DataFactory

  beforeEach(module('app'));

  beforeEach(inject(function($rootScope, $controller, _DataFactory_) {
    $scope = $rootScope.$new()
    DataFactory = _DataFactory_
    instantiateController = function() {
      $controller('DataController', {
        $scope: $scope,
        DataFactory: DataFactory
      })
    }
  }))

  // It shows that controller chenges $scope.results
  it('Calculates results', function() {
    expect($scope.results).toBe(undefined)
    instantiateController()
    expect($scope.results).toBe(5)
  })

  // It shows that DataFactory was called
  it('Calls `DataFactory.something`', function() {
    spyOn(DataFactory, 'something');
    instantiateController()
    expect(DataFactory.something).toHaveBeenCalled()
  })
});
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-mocks.js"></script>

查看更多
登录 后发表回答