Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally mock object in angularjs for jasmine/karma testing

I have an object that I am mocking up for unit testing. Essentially in my test file I mock it up as follows:

var mockObject = {
    mockMethod1 : function() {return true},
    mockMethod2 : function() {return true}
};


beforeEach(module('myModule') , function ($provide) {
    $provide.value('realObject',mockObject);
});

The way i understand it is that as I test functionality in my module etc... anywhere that references the "realObject" will use my "mockObject"

My issue is that I have made multiple js files for testing and I do not want to define my "mockObject" in each one of them ... nor do i want to maintain it in any more places than i have too.

Is there a way to move my "mockObjact" to a seperate file that gets included in karma.conf.js that will make the "mockObject" available for injection into any of my test files ..... Im thinking along the lines of how you inject $rootScope

like image 557
Deslyxia Avatar asked Apr 04 '14 17:04

Deslyxia


People also ask

What Jasmine function creates a mock object?

Jasmine uses spies to mock asynchronous and synchronous function calls. As with most mocking frameworks, you can set the externally observed behavior of the code you are mocking.

Does AngularJS use Jasmine?

The Angular CLI downloads and installs everything you need to test an Angular application with the Jasmine test framework.

What is the role of Jasmine and karma in Angular testing?

Jasmine is a behavior-driven development framework for testing JavaScript code that plays very well with Karma. Similar to Karma, it's also the recommended testing framework within the Angular documentation as it's setup for you with the Angular CLI. Jasmine is also dependency free and doesn't require a DOM.


1 Answers

You can create a global beforeEach function if it is written outside the context of a specific suite, but still executed by Jasmine, e.g. create a custom file to load by Karma and write your beforeEach function there without enclosing it in a describe function.

Example:

var myGlobal;

beforeEach(function() {
    // This will run before any it function.
    // Resetting a global state so the change in this function is testable
   myGlobal = 10
});

describe('first suite', function(){
  it('is a test', function(){
      expect(myGlobal).toBe(10);
      // Set the value to show that beforeEach is executed for each it function
      myGlobal = 20;
      expect(myGlobal).toBe(20);
  });

  it('is another test', function(){
      expect(myGlobal).toBe(10);
      myGlobal = 30;
      expect(myGlobal).toBe(30);
  });
});

describe('second suite', function(){
  it('is a test', function(){
      expect(myGlobal).toBe(10);
  });
});

See fiddle here

like image 105
Eitan Peer Avatar answered Sep 27 '22 20:09

Eitan Peer