Globally mock object in angularjs for jasmine/karma testing

时光总嘲笑我的痴心妄想 提交于 2019-12-04 01:54:33

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

You could build a service that houses your mock, and inject that service in each test file.

beforeEach(inject(function($rootScope, $controller, yourMockSvc) {
    appScope = $rootScope.$new();
    appCtrl = $controller('AppController', {
        $scope: appScope,
        yourSvc: yourMockSvc
    });
}));

Just define your mock object inside of another file and export it. You should be able to use it in any file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!