简体   繁体   中英

Struggling to setup Jasmine with RequireJS. Module's relative paths in define break when calling from test framework.

I have a project with which I have just recently introduced RequireJS. Before RequireJS, I had been testing my project with Jasmine. I am now trying to update Jasmine's SpecRunner so that it can handle RequireJS.

I found this article on unit testing with RequireJS and Jasmine which I have used to get me started. I've hit a snag with how I am loading modules. Each modules defines other modules it has a dependency on, but each module's load path is relative to the location where requireJS was loaded.

I load requireJS in two different locations: background.html and SpecRunner.html. Background is for the main application and SpecRunner is for testing. The problem is that my modules fail to load when called from SpecRunner because their relative paths change.

Example:

With this folder hierarchy and files I have two scenarios. One in which the code runs properly and one in which there is an issue:

Good Scenario

  • background.html loads require.js and executes targeting player.js as the loading point.
  • player.js defines playlists.js as a dependency.
  • playlists.js is loaded.
  • player.js is loaded.

Bad Scenario

  • SpecRunner.html loads require.js and executes targeting player.js as the loading point.
  • player.js defines playlists.js as a dependency.
  • playlists.js fails to load. GET file://tests/playlists.js
    • The file location is incorrect. playlists.js is not under /tests, it is under js/background!

I'm not sure how I should handle this? It seems like being extremely explicit with path names is my only way out, but that goes against all of the requireJS examples.

Paths in require are relative to the data-main location or relative to the location of the function that called require() . In your good scenario this is js/background/ , and in your bad scenario this is tests/ . In the blog you linked they use require.paths to make this work properly:

<!--
    Since we are in the "test" directory, not in the standard
    "js" directory, we need to define the path prefix' for the
    RequireJS modules so that the modules can be found from the
    tests running in the Spec directory.
-->
<script type="text/javascript">

    var require = {
        paths: {
            "domReady": "../js/lib/require/domReady",
            "model": "../js/model"
        }
    };

</script>

In your case, you'll have to set up paths like

'player':    '../js/background/player.js',
'playlists': '../js/background/playlists.js'

and explicitly require player and your spec in your test runner as they do in the blog post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM