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:
- js/third_party/jquery-1.7.2.min.js
- js/background/player.js
- js/background/playlists.js
- tests/SpecRunner.html
- tests/spec/PlayerSpec.js
- background.html
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 isjs/background/, and in your bad scenario this istests/. In the blog you linked they use require.paths to make this work properly:In your case, you’ll have to set up paths like
and explicitly require player and your spec in your test runner as they do in the blog post.