Mock a namespace and a function with the same name

Let's assume the following library:

javascript
const library = {
    
    print: () => 'hello'
    
}

library.print.value = 25;

export default library;

Let's call the function and the namespace:

javascript
console.log(library.print()); // 'hello'
console.log(library.print.value); // 25

As you can see, the function library.print() and the namespace library.print have the same name.

This becomes a problem if you want to test the function, for example, if you want to use the spyOn() function in Jest. To avoid conflicts, an option would be to export function and namespace using different names from a new file:

javascript
import library from 'library';

export const libraryPrintValue = library.print.value;
export default library;

On your component:

javascript
import library, { libraryPrintValue } from NewFile;

let a = library.print();
let b = libraryPrintValue;

And the test:

javascript
jest.spyOn(library, 'print').mockImplementation(() => 'Build your own mock');

Firebase

If you are using Firebase Realtime Database, you'll have a function with the same name as a namespace.

Simplified example:

javascript
const firebase = {
    
    database: function serviceNamespace () {
        
        return 'databaseRef';
        
    }
    
}

firebase.database.ServerValue = function increment (num) {
    
    return {sv: num};
    
}

export default firebase;

Let's print in the console the following:

javascript
console.log(firebase.database()); 
// 'databaseRef'

console.log(firebase.database.ServerValue);   
// ƒ increment () { return {sv: num}; }

As you can see, firebase.database() executes serviceNamespace(), whereas firebase.database.ServerValue returns the increment function.

Using the example from above, you can export function and namespace with different names:

javascript
import firebase from 'firebase';

export const firebaseServerValue = firebase.database.ServerValue;
export default firebase;

On your component:

javascript
import firebase, { firebaseServerValue } from 'NewFile';

let a = firebase.database().ref('ref').transaction(val => val + 1);
let b = firebaseServerValue.increment(1);

And the test:

javascript
jest.spyOn(firebase, 'database').mockImplementation(() => 'Build your own mock');

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.