在angularjs茉莉花/人缘全球测试模拟对象 [英] Globally mock object in angularjs for jasmine/karma testing

查看:115
本文介绍了在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 = {
    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);
  });
});

请参阅小提琴这里

这篇关于在angularjs茉莉花/人缘全球测试模拟对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆