在angularjs茉莉花/人缘全球测试模拟对象茉莉花、人缘、对象、测试

由网友(兽性打败理性)分享简介:我有我嘲笑了单元测试的对象。基本上在我的测试文件中我嘲笑起来如下: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 =...

我有我嘲笑了单元测试的对象。基本上在我的测试文件中我嘲笑起来如下:

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);
});

我理解的方式是,当我在测试我的模块等功能......任何地方引用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"

我的问题是,我已经测试多个js文件,我不希望他们每个人来定义我的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.

有没有动我mockObjact来这是包含在karma.conf.js一个单独的文件,这将使mockObject可注入到我的任何测试文件的方式.....林一起思考怎么行你注入$ rootScope

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

推荐答案

如果它是一个特定套件的环境之外书面您可以创建一个全局beforeEach功能,但仍茉莉花,例如执行创建一个自定义文件由噶装载有写你beforeEach功能,而不在描述功能括起来。

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.

例如:

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);
  });
});

请参阅小提琴这里

阅读全文

相关推荐

最新文章