user2918673
user2918673

Reputation: 163

Angular JS Unit Testing using Jasmine

I have a factory service as below 

FamilyService.js

(function(){ 'use strict';

angular.module('app')
.factory('ABC', FamilyService);

FamilyService.$inject = ['DEF'];
function FamilyService(DEF) {


function returnTrue() {
    var a="true";

}       

}

}());

    I want to call returnTrue method in My test case

 **TestFamilyService.js**

describe('testing my_controller.my_function', function () { var mockedFactory, $rootScope, $controller;

  beforeEach(module('app', function($provide) {
    mockedFactory = {
      save: jasmine.createSpy()
    };

    $provide.value('ABC', mockedFactory);
  }));




  it('should call the save function', function() {

    expect(mockedFactory.returnTrue()).toHaveBeenCalled();
  });
});



     **specrunner.html**


<!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Jasmine Spec Runner v2.4.1</title>

      <link rel="shortcut icon" type="image/png" href="lib/jasmine-2.4.1/jasmine_favicon.png">
      <link rel="stylesheet" href="lib/jasmine-2.4.1/jasmine.css">

      <script src="lib/jasmine-2.4.1/jasmine.js"></script>
      <script src="lib/jasmine-2.4.1/jasmine-html.js"></script>
      <script src="lib/jasmine-2.4.1/boot.js"></script>
      <script src="lib/jasmine-2.4.1/angular.js"></script>
      <script src="lib/jasmine-2.4.1/angular-mocks.js"></script>


      <!-- include source files here... -->
      <script src="src/Player.js"></script>
      <script src="src/webapp/Mock.js"></script>
      <script src="src/webapp/FamilyService.js"></script>




      <!-- include spec files here... -->

      <script src="spec/TestFamilyService.js"></script>

    </head>

    <body>
    </body>
    </html>

When i run specrunner.html in the browser it displays

Error: No module: app

TypeError: Unable to get value of the property 'returnTrue': object is null or undefined

Please Tel me whats wrong here?

Upvotes: 0

Views: 258

Answers (1)

Tobias Timm
Tobias Timm

Reputation: 2050

In FamilyService.js

angular.module('app').factory('ABC', FamilyService);

you are creating a factory for the existing module app, but if the module doesn't exist you need to write

angular.module('app',[]).factory('ABC', FamilyService);

In your case just create a new file, where the angular module gets created

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

UPDATE

Just include the dependencies of your module in the html

 <script src="lib/angular-sanititze/angular-sanitize.js"></script>

If you want to mock these modules, you can do something like

beforeEach(function() {
       angular.module('second',[]);
}

But in the case that you are using some methods of the third party library, you need to mock these methods as well.

Upvotes: 1

Related Questions