javascriptunit-testinghapi.js-lab

Override Global require on lab testing framework


I'm using hapi's lab+code testing framework. I need to override the global require function. I'm using mockery but I also tried to manually override it without any luck. Seems that lab executes all the code on a sandboxed environment where a special require function is provided instead of the global one. How can I properly override the global require function on the lab framework?

Thanks in advance.


Solution

  • I ended using proxyquire, which provides a clear and declarative way of mocking modules required by other modules, instead of creating or overriding any globals. Basically you create a require function that you use instead of the normal require to require the modules you want to test. Then, when that module makes a require of something you have declared as mock the wrapping require will provide the mock instead of the original package. It has the advantage that you can define partial mockups, so it will return a proxy that has the mocked methods as mockup and the rest of the methods will be forwarded to the original package.

    Here is an usage example

    // Mockups
    const ProxyQuire = require( 'proxyquire' );
    const mockupPaths = {
        'mongodb': require( './__mocks__/mongo' ),
        'fs': {
            readFileSync( path ) {
    
                if ( path !== 'PATH/TO/CERTS' ) {
                    return Fs.readFileSync( path );
                }
                return 'A VERY LONG STRING THAT LOOKS LIKE A CERTIFICATE!!';
            }
        }
    };
    
    // What we want to test
    
    const Connect = ProxyQuire( '../src/db-connect.js', mockupPaths );