Подтвердить что ты не робот

Действительно ли Jasmine 2.0 не работает с require.js?

Я настраиваю свои SpecRunner.html/.js, RequireConfig.js, мои пути и мои прокладки так же, как у меня с более ранними кандидатами на выпуск Jasmine + RequireJs, но теперь мои тестовые методы показывают Jasmine undefined. Недавно они изменили другой способ загрузки Jasmine, который, как я понимаю, несовместим с RequireJs.

Правильно ли я понимаю? Если да, можно ли снова использовать Jasmine + RequireJs?

4b9b3361

Ответ 1

Новый boot.js выполняет кучу инициализации и присоединяет его к window.onload(), который уже вызывается к моменту require.js, загружает Jasmine. Вы можете вручную вызвать window.onload() для инициализации HTML-репортера и выполнения среды.

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">

    <!-- specRunner.js runs all of the tests -->
    <script data-main="specRunner" src="../bower_components/requirejs/require.js"></script>
  </head>
  <body>
  </body>
</html>

specRunner.js

(function() {
  'use strict';

  // Configure RequireJS to shim Jasmine
  require.config({
    baseUrl: '..',
    paths: {
      'jasmine': 'tests/lib/jasmine-2.0.0/jasmine',
      'jasmine-html': 'tests/lib/jasmine-2.0.0/jasmine-html',
      'boot': 'tests/lib/jasmine-2.0.0/boot'
    },
    shim: {
      'jasmine': {
        exports: 'window.jasmineRequire'
      },
      'jasmine-html': {
        deps: ['jasmine'],
        exports: 'window.jasmineRequire'
      },
      'boot': {
        deps: ['jasmine', 'jasmine-html'],
        exports: 'window.jasmineRequire'
      }
    }
  });

  // Define all of your specs here. These are RequireJS modules.
  var specs = [
    'tests/spec/routerSpec'
  ];

  // Load Jasmine - This will still create all of the normal Jasmine browser globals unless `boot.js` is re-written to use the
  // AMD or UMD specs. `boot.js` will do a bunch of configuration and attach it initializers to `window.onload()`. Because
  // we are using RequireJS `window.onload()` has already been triggered so we have to manually call it again. This will
  // initialize the HTML Reporter and execute the environment.
  require(['boot'], function () {

    // Load the specs
    require(specs, function () {

      // Initialize the HTML Reporter and execute the environment (setup by `boot.js`)
      window.onload();
    });
  });
})();

Пример spec

define(['router'], function(router) {
  'use strict';

  describe('router', function() {
    it('should have routes defined', function() {
      router.config({});
      expect(router.routes).toBeTruthy();
    });
  });
});

Ответ 2

В альтернативном подходе, который может быть проще в некоторых случаях, используйте асинхронную поддержку Jasmine для загрузки вашего модуля AMD перед выполнением тестов, например:

в MySpec.js:

describe('A suite', function() {
  var myModule;

  // Use require.js to fetch the module
  it("should load the AMD module", function(done) {
    require(['myModule'], function (loadedModule) {
      myModule = loadedModule;
      done();
    });
  });

  //run tests that use the myModule object
  it("can access the AMD module", function() {
    expect(myModule.speak()).toBe("hello");
  });
});

Для этого вам необходимо включить require.js в свой SpecRunner.html и, возможно, настроить (как обычно, например, путем установки baseUrl), например:

в SpecRunner.html:

<!DOCTYPE HTML>
<html>
  <head>
    <meta 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">

    <script src="lib/require.min.js"></script>
    <script> require.config({ baseUrl: "src" }); </script>

    <script src="lib/jasmine-2.0.0/jasmine.js"></script>
    <script src="lib/jasmine-2.0.0/jasmine-html.js"></script>
    <script src="lib/jasmine-2.0.0/boot.js"></script>

    <script src="spec/MySpec.js"></script>

  </head>
  <body>
  </body>
</html>

В этом примере реализация модуля AMD может выглядеть примерно так:

в src/myModule.js:

define([], function () {
  return {
    speak: function () {
      return "hello";
    }
  };
});

Здесь рабочий Plunk, который реализует этот полный пример.

Наслаждайтесь!