Skip to content

Instantly share code, notes, and snippets.

@arian
Created August 4, 2011 10:00
Show Gist options
  • Save arian/1124879 to your computer and use it in GitHub Desktop.
Save arian/1124879 to your computer and use it in GitHub Desktop.
Function.bind specs
// New:
describe('Function.bind', function(){
it('should still be possible to use it as constructor', function(){
function Alien(type) {
this.type = type;
}
var thisArg = {};
var Tribble = Alien.bind(thisArg, 'Polygeminus grex');
// `thisArg` should **not** be used for the `this` binding when called as a constructor
var fuzzball = new Tribble('Klingon');
expect(fuzzball.type).toEqual('Polygeminus grex');
});
it('when using .call(thisArg) on a bound function, it should ignore the thisArg of .call', function(){
var fn = function(){
return [this.foo].concat(Array.slice(arguments));
};
expect(fn.bind({foo: 'bar'})()).toEqual(['bar'])
expect(fn.bind({foo: 'bar'}, 'first').call({foo: 'yeah!'}, 'yooo')).toEqual(['bar', 'first', 'yooo']);
var bound = fn.bind({foo: 'bar'});
var bound2 = fn.bind({foo: 'yep'});
var inst = new bound;
inst.foo = 'noo!!';
expect(bound2.call(inst, 'yoo', 'howdy')).toEqual(['yep', 'yoo', 'howdy']);
});
});
// What we already had:
describe('Function.bind', function(){
it('should return the function bound to an object', function(){
var spy = jasmine.createSpy();
var f = spy.bind('MooTools');
expect(spy).not.toHaveBeenCalled();
f();
expect(spy).toHaveBeenCalledWith();
f('foo', 'bar');
expect(spy).toHaveBeenCalledWith('foo', 'bar');
});
it('should return the function bound to an object with specified argument', function(){
var binding = {some: 'binding'};
var spy = jasmine.createSpy().andReturn('something');
var f = spy.bind(binding, 'arg');
expect(spy).not.toHaveBeenCalled();
expect(f('additional', 'arguments')).toEqual('something');
expect(spy.mostRecentCall.object).toEqual(binding);
});
it('should return the function bound to an object with multiple arguments', function(){
var binding = {some: 'binding'};
var spy = jasmine.createSpy().andReturn('something');
var f = spy.bind(binding, ['foo', 'bar']);
expect(spy).not.toHaveBeenCalled();
expect(f('additional', 'arguments')).toEqual('something');
expect(spy.mostRecentCall.object).toEqual(binding);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment