让requirejs与Jasmine一起使用


67

我首先要说的是,我是RequireJS的新手,甚至是茉莉花的新手。

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

看来,如果测试中抛出错误(我可以特别想到一个错误,即类型错误),则将显示spec运行器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;
        }
    };
});

以及注释来源(JIC):

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

    return note;
});

我已经确保就应用程序而言,路径是正确的。一旦完成这项工作,我就可以配置该路径,这样就不会太麻烦了。


你可以试试这个吗?在require之外定义了HtmlReported。调用仅在内部执行。var jasmineEnv = jasmine.getEnv(); jasmineEnv.addReporter(new jasmine.HtmlReporter()); require(['suites / aSpec.js'],function(spec){jasmineEnv.execute();});
2013年

1
:茉莉2.0.0独立的,这样的回答为我工作stackoverflow.com/questions/19240302/...
shaunsantacruz

Answers:


58

我设法通过一些反复试验使它工作。主要问题是,编写规范时并不需要创建,而要使用define:

原版的:

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()使用的所有内容都必须包装在定义中(我想现在看来很明显)。您可以看到,在specRunner.js文件中,执行测试时使用了require(因此需要“定义”规范。

另一个问题是,在创建规范时,describe()和it()是必需的(不仅仅是像我在发布的示例中那样的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
+1是主要问题,当您编写规范时,并不需要创建,而是要使用define。如果使用require,您的测试有时会工作,有时不会出现错误,没有找到规范
Lukas Cenovsky 2013年

12

只是将其添加为您正在使用Jasmine 2.0独立版的用户的替代答案。我相信这也可以适用于Jasmine 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>

现在这是一个规范文件示例:

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

这是Jasmine 2.0文档中异步支持部分的链接:http : //jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support


值得注意的是,这是我发现与node-webkit结合使用以及RequireJS r.js插件一起使用的唯一解决方案,因此我可以测试导入AMD和Node.js模块的代码。
jmort253 2014年

您的规格未使用amd,我认为这是此问题的全部目的。
cancerbero

3

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

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

理想规格示例:spec / 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文件,就不需要做任何其他事情。

为了使所有这些正常工作,我们创建了一个启动文件,并将Jasmine配置为使用该文件(http://jasmine.github.io/2.0/boot.html),并添加了一些魔术效果,可以暂时将运行测试推迟到之后我们已经加载了我们的部门:

我们的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语法规范保存在堆栈中,将其弹出,需要模块,在其中包含我们的断言的情况下执行回调,然后在完成所有加载后运行Jasmine。

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


3

您可以结合使用donebefore过滤器来测试异步回调:

  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="https://stackoverflow.com/jasmine/lib/jasmine-2.1.3/jasmine_favicon.png">
<link rel="stylesheet" href="https://stackoverflow.com/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();
})
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.