Make require.stub() optionally accept a factory function

require.stub() can now accept a factory function instead of an object
so that stubbed modules are initialized lazily:

require.stub('zlib', function() {
    // initialized once, when zlib first required
    return {
        createGzip: function() { ... }
    };
});

http://code.google.com/p/phantomjs/issues/detail?id=1044
This commit is contained in:
Juliusz Gonera
2013-02-05 00:04:17 -08:00
committed by Ariya Hidayat
parent 1e5638678d
commit 2d42b52c67
2 changed files with 20 additions and 0 deletions
+3
View File
@@ -276,6 +276,9 @@ phantom.callback = function(callback) {
// first see if there are any stubs for the request
if (this.stubs.hasOwnProperty(request)) {
if (this.stubs[request].exports instanceof Function) {
this.stubs[request].exports = this.stubs[request].exports();
}
return this.stubs[request].exports;
}
+17
View File
@@ -86,6 +86,23 @@ describe("require()", function() {
require('stubbed');
}).should.Throw("Cannot find module 'stubbed'");
});
describe("when invoked with a factory function", function() {
var count = 0;
require.stub('lazily_stubbed', function() {
++count;
return 'lazily stubbed module';
});
it("initializes the module lazily", function() {
require('lazily_stubbed').should.equal('lazily stubbed module');
});
it("doesn't reinitialize the module each time it's required", function() {
require('lazily_stubbed');
count.should.equal(1);
});
});
});
describe("when the path is relative", function() {