Evan Hobbs
Evan Hobbs

Reputation: 3672

Patch/mock function inside another function for testing in javascript

Basically I'd like to patch functions that another function calls so that I can confirm they've been called. Is this possible in js? (I'm using Mocha/Chai/Sinon for testing).

A simplified version of what I'd like to do:

// in render.js
export helper = function() {}
export default = function() {
  helper()
}

// in the render-test.js
import render, { helper } from 'render'
// what I'd like to to:
helper = sinon.spy()
render()
assert(helper.called, true)

Upvotes: 2

Views: 1272

Answers (1)

robertklep
robertklep

Reputation: 203534

It's possible, but it does require some rewriting, most notably the way you're calling helper in render.js.

Here's an example that works:

// render.js
export function helper() {}
export default function() {
  exports.helper()
}

// render-test.js
import render, * as renderFuncs from 'render'
...
sinon.spy(renderFuncs, 'helper');
render()
assert(renderFuncs.helper.called)

The reason you need to call exports.helper() instead of just helper() is because the latter is a local reference to the helper function, which you can't access from the test file.

The exports object is accessible from the test file (it's given the name renderFuncs), so Sinon can change the reference to helper and wrap it with a spy.

Upvotes: 4

Related Questions