2013-05-07 62 views
63

我首先想说的是,我是RequireJS的新手,甚至是Jasmine的新手。获取requirejs与Jasmine一起工作

我遇到了一些与SpecRunner有关的问题,需要JS。我一直在关注Uzi Kilon和Ben Nadel的教程(以及其他一些),他们帮助了一些人,但我仍然有一些问题。

看来,如果在测试中出现错误(我可以想到一个特别的类型错误),spec runner html会显示。这告诉我,我在JavaScript中有一些问题。但是,在我解决这些错误之后,不再显示HTML。 我无法让测试运行器显示。有人会发现我的代码有问题会导致此问题?

这里是我的目录结构

Root 
|-> lib 
    |-> jasmine 
     |-> lib (contains all of the jasmine lib) 
     |-> spec 
     |-> src 
    |-> jquery (jquery js file) 
    |-> require (require js file) 
index.html (spec runner) specRunner.js 

这里是SpecRunner(指数)HTML

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>Javascript Tests</title> 

     <link rel="stylesheet" href="lib/jasmine/lib/jasmine.css"> 

     <script src="lib/jasmine/lib/jasmine.js"></script> 
     <script src="lib/jasmine/lib/jasmine-html.js"></script> 
     <script src="lib/jquery/jquery.js"></script> 
     <script data-main="specRunner" src="lib/require/require.js"></script> 

     <script> 
      require({ paths: { spec: "lib/jasmine/spec" } }, [ 
        // Pull in all your modules containing unit tests here. 
        "spec/notepadSpec" 
       ], function() { 
        jasmine.getEnv().addReporter(new jasmine.HtmlReporter()); 
        jasmine.getEnv().execute(); 
       }); 
     </script> 

    </head> 

<body> 
</body> 
</html> 

这里是specRunner.js(配置)

require.config({ 
    urlArgs: 'cb=' + Math.random(), 
    paths: { 
     jquery: 'lib/jquery', 
     jasmine: 'lib/jasmine/lib/jasmine', 
     'jasmine-html': 'lib/jasmine/lib/jasmine-html', 
     spec: 'lib/jasmine/spec/' 
    }, 
    shim: { 
     jasmine: { 
      exports: 'jasmine' 
     }, 
     'jasmine-html': { 
      deps: ['jasmine'], 
      exports: 'jasmine' 
     } 
    } 
}); 

这里有一个规范:

require(["../lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual(""); 


    }); 
}); 

记事本来源:

define(['lib/jasmine/src/note'], function (note) { 

    var notes = [ 
     new note('pick up the kids', 'dont forget to pick up the kids'), 
     new note('get milk', 'we need two gallons of milk') 
    ]; 


    return { 
     noteTitles: function() { 
      var val; 

      for (var i = 0, ii = notes.length; i < ii; i++) { 
       //alert(notes[i].title); 
       val += notes[i].title + ' '; 
      } 

      return val; 
     } 
    }; 
}); 

和NOTE源(JIC):

define(function(){ 
    var note = function(title, content) { 
     this.title = title; 
     this.content = content; 
    }; 

    return note; 
}); 

我已经确定的是,就应用程序而言,路径是正确的。一旦我得到这个工作,我可以玩弄配置这些路径,以便它不那么难过。

+0

你能尝试这个?在需求之外定义HtmlReported。只调用里面执行。 var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter(new jasmine.HtmlReporter()); require(['suites/aSpec.js'],function(spec){jsmineEnv.execute(); }); – basos 2013-05-11 11:39:20

+1

对于茉莉花2.0.0独立,这个答案适合我: http://stackoverflow.com/questions/19240302/does-jasmine-2-0-really-not-work-with-require-js/20851265#20851265 – shaunsantacruz 2014-02-19 19:16:38

回答

55

我设法得到这个工作与一些试验和错误。主要的问题是,当你写的规格是不是要求您要创建,要使用定义:

原文:

require(["/lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 


    }); 
}); 

工作:

define(["lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk "); 
     }); 

    }); 
}); 

在做了一些研究之后,很明显的是,当使用RequireJS时,任何你想require()使用的东西都必须被包装在一个define中(现在看来我觉得很明显)。您可以看到,在specRunner.js文件中,在执行测试时使用了一个require(因此需要“定义”规格。

另一个问题是,在创建规范时,describe()和它()是必要的(不仅仅像我在发布的例子中描述的那样)。

原文:

describe("returns titles", function() { 
     expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 


    }); 

工作:

describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk "); 
     }); 

    }); 

我也改变了围绕在测试运行存在,但是这是一个重构,并没有改变测试的结果。

同样,这里有文件和改变:

note.js:保持不变

notepad.js:保持不变

的index.html:

<!doctype html> 
<html lang="en"> 
    <head> 
     <title>Javascript Tests</title> 
     <link rel="stylesheet" href="lib/jasmine/lib/jasmine.css"> 
     <script data-main="specRunner" src="lib/require/require.js"></script> 
    </head> 

    <body> 
    </body> 
</html> 

个specRunner.js:

require.config({ 
    urlArgs: 'cb=' + Math.random(), 
    paths: { 
     jquery: 'lib/jquery', 
     'jasmine': 'lib/jasmine/lib/jasmine', 
     'jasmine-html': 'lib/jasmine/lib/jasmine-html', 
     spec: 'lib/jasmine/spec/' 
    }, 
    shim: { 
     jasmine: { 
      exports: 'jasmine' 
     }, 
     'jasmine-html': { 
      deps: ['jasmine'], 
      exports: 'jasmine' 
     } 
    } 
}); 


require(['jquery', 'jasmine-html'], function ($, jasmine) { 

    var jasmineEnv = jasmine.getEnv(); 
    jasmineEnv.updateInterval = 1000; 

    var htmlReporter = new jasmine.HtmlReporter(); 

    jasmineEnv.addReporter(htmlReporter); 

    jasmineEnv.specFilter = function (spec) { 
     return htmlReporter.specFilter(spec); 
    }; 

    var specs = []; 

    specs.push('lib/jasmine/spec/notepadSpec'); 



    $(function() { 
     require(specs, function (spec) { 
      jasmineEnv.execute(); 
     }); 
    }); 

}); 

notepadSpec.js:

define(["lib/jasmine/src/notepad"], function (notepad) { 
    describe("returns titles", function() { 

     it("something", function() { 

      expect(notepad.noteTitles()).toEqual("pick up the kids get milk"); 
     }); 

    }); 
}); 
+1

对于_的主要问题是,当您编写规范时,它不是您要创建的要求,而是要使用define_。如果您使用require,您的测试有时可以正常工作,有时不会出现错误_no specs found_。 – 2013-12-30 22:37:24

12

刚刚添加该为您使用的茉莉花2.0独立的人谁的替代答案。我相信这也适用于茉莉花1.3,但异步语法是不同的,有点丑陋。

这是我修改SpecRunner.html文件:

<!DOCTYPE HTML> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Jasmine Spec Runner v2.0.0</title> 

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

    <!-- 
    Notice that I just load Jasmine normally 
    -->  
    <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine.js"></script> 
    <script type="text/javascript" src="lib/jasmine-2.0.0/jasmine-html.js"></script> 
    <script type="text/javascript" src="lib/jasmine-2.0.0/boot.js"></script> 

    <!-- 
    Here we load require.js but we do not use data-main. Instead we will load the 
    the specs separately. In short we need to load the spec files synchronously for this 
    to work. 
    --> 
    <script type="text/javascript" src="js/vendor/require.min.js"></script> 

    <!-- 
    I put my require js config inline for simplicity 
    --> 
    <script type="text/javascript"> 
    require.config({ 
     baseUrl: 'js', 
     shim: { 
      'underscore': { 
       exports: '_' 
      }, 
      'react': { 
       exports: 'React' 
      } 
     }, 
     paths: { 
      jquery: 'vendor/jquery.min', 
      underscore: 'vendor/underscore.min', 
      react: 'vendor/react.min' 
     } 
    }); 
    </script> 

    <!-- 
    I put my spec files here 
    --> 
    <script type="text/javascript" src="spec/a-spec.js"></script> 
    <script type="text/javascript" src="spec/some-other-spec.js"></script> 
</head> 

<body> 
</body> 
</html> 

现在,这里是一个例子spec文件:

describe("Circular List Operation", function() { 

    // The CircularList object needs to be loaded by RequireJs 
    // before we can use it. 
    var CircularList; 

    // require.js loads scripts asynchronously, so we can use 
    // Jasmine 2.0's async support. Basically it entails calling 
    // the done function once require js finishes loading our asset. 
    // 
    // Here I put the require in the beforeEach function to make sure the 
    // Circular list object is loaded each time. 
    beforeEach(function(done) { 
     require(['lib/util'], function(util) { 
      CircularList = util.CircularList; 
      done(); 
     }); 
    }); 

    it("should know if list is empty", function() { 
     var list = new CircularList(); 
     expect(list.isEmpty()).toBe(true); 
    }); 

    // We can also use the async feature on the it function 
    // to require assets for a specific test. 
    it("should know if list is not empty", function(done) { 
     require(['lib/entity'], function(entity) { 
      var list = new CircularList([new entity.Cat()]); 
      expect(list.isEmpty()).toBe(false); 
      done(); 
     }); 
    }); 
}); 

这里是一个链接从茉莉花2.0文档的异步支持部分:http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support

+0

值得注意的是,这是我发现与[node-webkit](https://github.com/rogerwang/node-webkit)一起使用的唯一解决方案,与[RequireJS r.js插件](http:///requirejs.org/docs/1.0/docs/node.html),以便我可以测试导入AMD和Node.js模块的代码。 – jmort253 2014-05-07 19:59:02

+0

你的规格没有使用amd,我认为这是这个问题的全部目的。 – cancerbero 2016-02-03 01:10:56

3

Jasmine 2.0 standalone的另一个选择是创建一个boot.js文件,并将其设置为在所有AMD模块加载后运行测试。

在我们的例子中编写测试的理想最终用户案例是不必一次性列出我们所有的spec文件或依赖项,并且只需要将* spec文件声明为具有依赖关系的AMD模块。

例理想规格:规格/ JavaScript的/ sampleController_spec.js

require(['app/controllers/SampleController'], function(SampleController) { 
    describe('SampleController', function() { 
     it('should construct an instance of a SampleController', function() { 
     expect(new SampleController() instanceof SampleController).toBeTruthy(); 
     }); 
    }); 
}); 

理想的情况下加载的依赖和运行规范的背景行为是完全不透明的人来上这个项目希望编写测试,除了用AMD依赖创建一个* spec.js文件之外,他们不需要做任何事情。

为了得到这一切的工作,我们创建了一个启动文件和配置茉莉花使用它(http://jasmine.github.io/2.0/boot.html),并增加了一些魔法环绕需要暂时推迟运行测试,直到经过我们加载我们DEPS:

我们boot.js'‘执行’部分:

/** 
* ## Execution 
* 
* Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. 
*/ 

var currentWindowOnload = window.onload; 

// Stack of AMD spec definitions 
var specDefinitions = []; 

// Store a ref to the current require function 
window.oldRequire = require; 

// Shim in our Jasmine spec require helper, which will queue up all of the definitions to be loaded in later. 
require = function(deps, specCallback){ 
    //push any module defined using require([deps], callback) onto the specDefinitions stack. 
    specDefinitions.push({ 'deps' : deps, 'specCallback' : specCallback }); 
}; 

// 
window.onload = function() { 

    // Restore original require functionality 
    window.require = oldRequire; 
    // Keep a ref to Jasmine context for when we execute later 
    var context = this, 
     requireCalls = 0, // counter of (successful) require callbacks 
     specCount = specDefinitions.length; // # of AMD specs we're expecting to load 

    // func to execute the AMD callbacks for our test specs once requireJS has finished loading our deps 
    function execSpecDefinitions() { 
    //exec the callback of our AMD defined test spec, passing in the returned modules. 
    this.specCallback.apply(context, arguments);   
    requireCalls++; // inc our counter for successful AMD callbacks. 
    if(requireCalls === specCount){ 
     //do the normal Jamsine HTML reporter initialization 
     htmlReporter.initialize.call(context); 
     //execute our Jasmine Env, now that all of our dependencies are loaded and our specs are defined. 
     env.execute.call(context); 
    } 
    } 

    var specDefinition; 
    // iterate through all of our AMD specs and call require with our spec execution callback 
    for (var i = specDefinitions.length - 1; i >= 0; i--) { 
    require(specDefinitions[i].deps, execSpecDefinitions.bind(specDefinitions[i])); 
    } 

    //keep original onload in case we set one in the HTML 
    if (currentWindowOnload) { 
    currentWindowOnload(); 
    } 

}; 

我们基本上保持我们的AMD语法规范的堆栈,弹出他们,需要的模块,执行与我们在它的断言回调,然后运行茉莉花一旦一切都完成加载。

这个设置使我们可以等到我们单个测试所需的所有AMD模块都加载完毕,并且不会通过创建全局变量来破坏AMD模式。实际上我们暂时覆盖了需求,并且只使用require(我们的`src_dir:jasmine.yml为空)加载我们的应用程序代码,但这里的总体目标是减少编写规范的开销。

+0

如果您使用Jasmine 2.0,很好的答案。像魅力一样工作.. – mehrandvd 2015-12-18 21:33:43

3

您可以组合使用done与之前的过滤器来测试异步回调:

beforeEach(function(done) { 
    return require(['dist/sem-campaign'], function(campaign) { 
     module = campaign; 
     return done(); 
    }); 
    }); 
1

这是我要怎么做才能运行使用所有我的消息来源和规格AMD/requirejs在HTML茉莉花规范。

这是加载茉莉,然后我的“单元测试启动”我的index.html文件:

<html><head><title>unit test</title><head> 
<link rel="shortcut icon" type="image/png" href="/jasmine/lib/jasmine-2.1.3/jasmine_favicon.png"> 
<link rel="stylesheet" href="/jasmine/lib/jasmine-2.1.3/jasmine.css"> 
<script src="/jasmine/lib/jasmine-2.1.3/jasmine.js"></script> 
<script src="/jasmine/lib/jasmine-2.1.3/jasmine-html.js"></script> 
<script src="/jasmine/lib/jasmine-2.1.3/boot.js"></script> 
</head><body> 
<script data-main="javascript/UnitTestStarter.js" src="javascript/require.js"></script> 
</body></html> 

,然后我UnitTestStarter.js是这样的:

require.config({ 
    "paths": { 
     .... 
}); 
require(['MySpec.js'], function() 
{ 
    jasmine.getEnv().execute(); 
})