使用RequireJS,Jasmine和testr进行JavaScript依赖注入

asc*_*oni 8 unit-testing dependency-injection requirejs jasmine

我只是在使用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>
Run Code Online (Sandbox Code Playgroud)

config.js ..

require.config({

  // Initialize specs.
  deps:["main"],
...
...
});
Run Code Online (Sandbox Code Playgroud)

main.js ..

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

spec\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');
  });
});
Run Code Online (Sandbox Code Playgroud)

today.js ..

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

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

谢谢.

jan*_*ith 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');
      });
    });
});
Run Code Online (Sandbox Code Playgroud)

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