jupiter / simple-mock

Super simple stubs and spies with 1-step sandbox restore
MIT License
87 stars 12 forks source link

Mocking simple function not working as expected #25

Closed arb closed 7 years ago

arb commented 7 years ago
const mockTarget = () => {
  console.log('mockTarget has been called')
}

const handler = () => mockTarget();

simple.mock(mockTarget).returnWith(undefined);

handler();

In this example, I would expect mockTarget to not be called, but it is when using simple-mock@0.7.3. Is this expected, am I using it wrong, or a 🐛 ?

HCanber commented 7 years ago

simple.mock (and simple.spy) used on function as in your example creates a standalone stub/spy, see https://github.com/jupiter/simple-mock#standalone-stubs-and-spies

so you have to called the returned function.

const fn = simple.mock(mockTarget).returnWith(undefined);
fn();

Or, you can replace functions on objects, so this will also work:

const o = { mockTarget }
const handler = () => o.mockTarget();

simple.mock(o, 'mockTarget').returnWith(undefined);

handler();