Angularjs Jasmine Service Dependency Injection

This tutorial will explain how to write the Jasmine unit test case for angularjs service dependency injection. End of the tutorial you will find the demo and download link.This tutorial will help to run the Jasmine unit test in browsers.

Let’s start the tutorial.

Below starting the project please create the project folder “jasmine” and create the below files and folder inside the project folder.


Open the spec/controller.js file and place the below code to that file

var app = angular.module('app', []);
app.controller('PasswordController', function($scope,serviceA) {
    $ = serviceA.getData();

Declare the angular module in the var (app) and use it to across to your all files. At the end of the project you will face error like below if we declaring the module each time when we creating the angular files and injecting the dependency instead of creating common module like above.

Error: [$injector:unpr] Unknown provider: serviceBProvider <- serviceB <- serviceA

Create Services methods.

Open spec/servicesA.js and place the below code.

           return serviceB.getServiceData();

Open spec/servicesB.js and place the below code.

       getServiceData : function(){
           return "serviceBData";

Create spec functions

Open spec/serviceASpec.js and place the below code.

describe('Service A', function () {
    var serviceA, serviceB;


    // Inject the dependancy for the testing data
    beforeEach(inject(function (_serviceA_,_serviceB_) {
        serviceA = _serviceA_;
        serviceB = _serviceB_;

    it('runServices.fnServices()', function () {


Open the jasmineSpec.html file and place the below code to that file

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Angularjs Jasmine Service Dependency Injection</title>

    <link rel="shortcut icon" type="image/png" href="jasmine_favicon.png">
    <!-- Jasmine dependency -->
    <link rel="stylesheet" href="">
    <script src=""></script>
    <script src=""></script>
    <script src=""></script>
	<!-- AngularJS dependency -->
    <script src=""></script>
    <script src=""></script>
    <!-- include source files here... -->
    <script src="spec/controller.js"></script>
    <script src="spec/serviceB.js"></script>
    <script src="spec/serviceA.js"></script>
    <script src="spec/serviceASpec.js"></script>

The demo will well work in any Jasmine unit test supported browsers and it don’t have dependency with Karma.


Latest posts by W3TWEAKS (see all)


Leave a Reply

Your email address will not be published. Required fields are marked *