Skip to content

Instantly share code, notes, and snippets.

@jackysee
Last active December 14, 2015 01:19
Show Gist options
  • Save jackysee/5005192 to your computer and use it in GitHub Desktop.
Save jackysee/5005192 to your computer and use it in GitHub Desktop.
Aware of globals in mocking using Squire.js

Aware of globals in mocking using Squire.js

A typical spec would be like:

define(['lib/Squire', 'jquery'], function(Squire, $){

	describe("a", function() {
  		var a;
  		beforeEach(function(){
  			var done = false;
  
  			runs(function () {
  				new Squire()
  				//.mock(...)
  				.require(['components/a'], function (aa){
  					a = aa;
  					done = true;
  				});
  			});
  
  			waitsFor(function(){
  				return done;
  			});
  		});
  
  
  		it("should be defined", function() {
  			expect(a).toBeDefined();
  		});
  
  		it("plugin should be defined", function(){
  			expect($.fn.aaa).toBeDefined();
  		});
  	});
});

where a.js looks like:

define(['jquery'], function($){
	$.fn.aaa = function() {
		this.addClass('aaa');
  	};
  	return $.fn.aaa;
});

But if you run the spec, it would result in will found $.fn.aaa to be undefined. The reason for that is because Squire is creating a new context for require.js, where a.js get a self $ reference, which is different from the outside one.

To fix this, you need to inject the jQuery from outside to Squire:

new Squire()
	.mock({
		jquery: function(){ return $; }
	})
	.require(['components/a'], function (aa){
		a = aa;
		done = true;
	});

Note that you cannot just feed in {jquery:$} to .mock(), as require.js will think the instance $, which is a function as the factory method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment