Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jasmine to test a service with uibModal and lodash as dependencies

This is my first time using Jasmine, and I have tested my first Factory without problems.

But now, I want to test this Service:

angular.module('Questions', [])
.service('QuestionsService', function($uibModal, $log, _) { 
  ... 
}

$uibModal is from UI Bootstrap (see here) and _ is Lodash.

My Jasmine test so far is:

describe('Service: QuestionsService', function() {

    var QuestionsService;

    beforeEach(inject(function(_QuestionsService_) {
      QuestionsService = _QuestionsService_;
    }));

    ...
}

And when I try it (grunt test), I get the following error:

Error: [$injector:unpr] Unknown provider: $uibModalProvider <- $uibModal <- QuestionsService

And at some point I also had:

Error: [$injector:unpr] Unknown provider: _Provider <- _ <- QuestionsService

If it can help, my Karma conf is:

module.exports = function(config) {
  'use strict';
  config.set({
    autoWatch: true,
    basePath: '../',

    frameworks: [
      "jasmine"
    ],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/lodash/lodash.js',
      'bower_components/angular/angular.js',
      'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-cookies/angular-cookies.js',
      'bower_components/angular-resource/angular-resource.js',
      'bower_components/angular-route/angular-route.js',
      'bower_components/angular-sanitize/angular-sanitize.js',
      'bower_components/angular-touch/angular-touch.js',
      'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      'bower_components/angular-mocks/angular-mocks.js',
      // endbower
      "app/scripts/**/*.js",
      "test/mock/**/*.js",
      "test/spec/**/*.js",
    ],
    exclude: [
    ],
    port: 8080,
    browsers: [
      "PhantomJS"
    ],
    plugins: [
      "karma-phantomjs-launcher",
      "karma-jasmine"
    ],
    singleRun: false,
    colors: true,
    logLevel: config.LOG_INFO,
  });
};
like image 295
didjoman Avatar asked Jan 11 '16 19:01

didjoman


1 Answers

Just in case others find this. To solve the error when testing a directive's controller, I mocked the $uibModal service, conceptually like this:

describe('Service: QuestionsService', function() {

    var controller;

    beforeEach(inject(function($controller) {
        controller = $controller('controllerName', {
            $uibModal : {}
        });
    }));

    ...
}

$uibModal may need to be more than just an empty object if you are writing tests against controller functions that interact with it.

like image 59
JeffryHouser Avatar answered Nov 18 '22 04:11

JeffryHouser