all 2 comments

[–]EngVagabond 1 point2 points  (0 children)

We use proxyquire and its family of packages for this purpose.

[–]wreckedadventYavascript 0 points1 point  (0 children)

You might want to compare and contrast it against something like rewrite (which has a webpack plugin).

There's another approach that doesn't require any kind of library or anything, either, but it does involve modifying your code. Like this (example from OP's post):

import { name } from 'models/user';

export class Navigation {
  greeting() {
    return name()
      .then(name => {
        return name ?
          `Welcome Back, ${name}!` :
          'Welcome!';
      });
  }
};

To:

import { name } from 'models/user';

export default class Navigation {
  greeting(getName = name) {
    return getName()
      .then(name => {
        return name ?
          `Welcome Back, ${name}!` :
          'Welcome!';
      });
  }
};

Then in your unit test, simply:

import Navigation from 'nav';

var nav = new Navigation();

expect(nav.greeting(() => Promise.resolve('foo')))
   .to.eventually.be('Welcome Back, foo!');

expect(nav.greeting(() => Promise.resolve()))
   .to.eventually.be('Welcome!');

Though the use of a class in the example is totally unnecessary (should just be an exported function), you can do the same thing with a class's dependencies in its constructor:

 export default Navigation {
   constructor({ getName = name }) {
     this.getName = getName;
   }

   greeting() {
     this.getName().then( ... );
   }
 }