Let's assume the following library:
javascriptconst library = { print: () => 'hello' } library.print.value = 25; export default library;
Let's call the function and the namespace:
javascriptconsole.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:
javascriptimport library from 'library'; export const libraryPrintValue = library.print.value; export default library;
On your component:
javascriptimport library, { libraryPrintValue } from NewFile; let a = library.print(); let b = libraryPrintValue;
And the test:
javascriptjest.spyOn(library, 'print').mockImplementation(() => 'Build your own mock');
If you are using Firebase Realtime Database, you'll have a function with the same name as a namespace.
Simplified example:
javascriptconst 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:
javascriptconsole.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:
javascriptimport firebase from 'firebase'; export const firebaseServerValue = firebase.database.ServerValue; export default firebase;
On your component:
javascriptimport firebase, { firebaseServerValue } from 'NewFile'; let a = firebase.database().ref('ref').transaction(val => val + 1); let b = firebaseServerValue.increment(1);
And the test:
javascriptjest.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.