-
-
Save danscotton/3164620 to your computer and use it in GitHub Desktop.
mocking with amd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ---------------------------------------- | |
// /path/to/dependency.js | |
define(function() { | |
return { | |
doSomethingWithIt: function() { | |
// blah | |
} | |
}; | |
}); | |
// ---------------------------------------- | |
// my_object.js | |
define(['/path/to/dependency'], function(myDependency) { | |
function MyObject() { | |
this.dependency = myDependency; | |
} | |
MyObject.prototype = { | |
one: function() { | |
this.dependency.doSomethingWithIt(); | |
return 'blah'; | |
} | |
}; | |
return MyObject; | |
}); | |
// ---------------------------------------- | |
// my_object_spec.js | |
// the object under test is my_object, so ideally | |
// I'd like to mock/stub myDependency | |
define(['my_object', '/path/to/dependency'], function(MyObject, myDependency) { | |
beforeEach(function() { | |
sinon.stub(myDependency, 'doSomethingWithIt').returns('whatever'); | |
this.subject = new MyObject(); | |
}); | |
afterEach(function() { | |
myDependency.doSomethingWithIt.restore(); | |
}); | |
it('should call one() as we expect', function() { | |
expect(this.subject.one(), 'blah'); | |
}); | |
}); |
I don't think you'd need to do this. Creating a property to hold a dependency is not needed if you already have the dependency available in closure scope. So in your one()
method, you just run myDependency.doSomethingWithIt()
directly. It's a bit hard to see what you're getting at without seeing a real-world example.
See you at Build. I will be found nursing a hangover in the Malmaison.
Hey @froots, just ran into a similar problem again this morning and I have a more concrete example that may explain things a little better of what we're trying to achieve: https://gist.github.com/3187758
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for you help Jim, much appreciated!
I've changed the example slightly...I tried doing this in the comment form but didn't get very far :/
If
my_object
were to return a constructor function instead, and then we used that dependency in some way in the constructor...do you think we could still use your example and pull the dependency into the test and stub it as before?Or if
myDependency
becameMyDependency
and returned a constructor itself, and we used:do you think we could still mock it?
Thanks again for the help – realised you're going to Build this year...will have to buy you a beer :)