【问题标题】:JavaScript dependency injection using RequireJS, Jasmine and testr使用 RequireJS、Jasmine 和测试的 JavaScript 依赖注入
【发布时间】:2012-09-20 19:21:09
【问题描述】:

我只是在使用 RequireJS 和 Jasmine 的单元测试策略中寻找依赖注入。我真的很喜欢testr 背后的想法,并且我尝试按照 github 中的示例设置 testr,但我不知道出了什么问题。我总是得到错误

错误:模块尚未加载:今天

当 testr 尝试加载要测试的模块时。

这里有一些上下文..

index.html ..

<script data-main="config" src="../../assets/js/libs/require.js"></script>
<script src="vendor/testr.js"></script>

config.js ..

require.config({

  // Initialize specs.
  deps:["main"],
...
...
});

ma​​in.js ..

require([
  // Load the example spec, replace this and add your own spec
  "spec/today"
], function() {
  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.execute();
});

规范\today.js ..

describe('Today print', function() {
  var date = {}, today;
  beforeEach(function() {
     date.today = new Date(2012, 3, 30);
     today = testr('today', {'util/date': date});  //Here is where the error is thrown
  });

  it('is user-friendly', function() {
     expect(today.getDateString()).toBe('Today is Monday, 30th April, 2012');
  });
});

today.js ..

define(['string', 'util/date'], function(string, date) {
  return {
    getDateString: function() {
      return string.format('Today is %d', date.today);
    }
  }
});

有没有人遇到过同样的问题? .我正在使用 RequireJS 2.0.6

谢谢。

【问题讨论】:

    标签: unit-testing dependency-injection requirejs jasmine


    【解决方案1】:

    在使用 testr 之前,需要从 requirejs 加载您的“今天”模块。 尝试类似:

    require(['today'], function(){
        describe('Today print', function() {
          var date = {}, today;
          beforeEach(function() {
             date.today = new Date(2012, 3, 30);
             today = testr('today', {'util/date': date});  //Here is where the error is thrown
          });
    
          it('is user-friendly', function() {
             expect(today.getDateString()).toBe('Today is Monday, 30th April, 2012');
          });
        });
    });
    

    另请阅读:http://cyberasylum.janithw.com/mocking-requirejs-dependencies-for-unit-testing/

    【讨论】:

    • 好的。我一直在努力让 testr 连续工作几天。这是我最近看到的示例项目。我使用 jasmine 为这个示例创建了一个 github 存储库(进行了一些小的调整)以与他人分享。但是,它仍然无法正常工作。任何人都可以在这里帮忙吗?谢谢。 github.com/loesak/jasmine-maven-require-testr
    • 我也有同样的问题。事实上,我在 require.config 中手动将它作为一个 dep 加载,并且 Karma 显示该文件正在被请求(首先)。
    猜你喜欢
    • 2012-01-11
    • 2020-06-09
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-14
    • 2020-09-09
    • 1970-01-01
    相关资源
    最近更新 更多