Marc On
Marc On

Reputation: 141

Sinon stub a function within a function

I'm bringing tests to our javascript files at my place of employment. I have decided to use Mocha, Chai and Sinon libraries to help with testing. I am starting out by writing unit tests for functions that don't need too much refactoring and ran into this interesting case that I don't really understand.

function getQueries() {
  code that returns queries in an array -> ['one', 'two', 'three']    
}

function sort(col, type) {
  var queries = getQueries();
  some code that sorts these queries
  return sorted array
}

Because I am unit testing the sort function I wanted to stub getQueries() to return a dummy list.

var queries = ['one', 'two', 'three'];
sinon.stub(getQueries).returns(queries);

The above code did not work error msg:

TypeError: Attempted to wrap undefined property undefined as function
at Object.wrapMethod (file://node_modules/sinon/pkg/sinon-1.17.7.js:1359:29)
at Object.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:3459:26)
at F.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4200:44)
at Context.obj.stub (file://node_modules/sinon/pkg/sinon-1.17.7.js:4215:37)
at Context.<anonymous> (unit_tests/unit_test.js:154:10)
at Context.sinonSandboxedTest (file:/node_modules/sinon/pkg/sinon-1.17.7.js:6069:39)

However, the code below did work properly.

var queries = ['one', 'two', 'three'];
getQueries = sinon.stub();
getQueries.returns(queries); 

I do not fully understand why this code works while the one above it doesn't. I know the syntax of sinon.stub(obj, method, function) but the getQueries is a function without an object. Any insight is greatly appreciated.

Upvotes: 1

Views: 6204

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

If getQueries seems to be no part of an object, it is part of the global object window, so sinon.stub(window, 'getQueries', ...) should do the trick.

An arguably better approach in this case would be to pass the result of getQueries to the sort function. In your current structure, the sort function has two jobs: getting the list and sorting it. You could maybe get away with naming the function getSortedQueries, but actual separation of concerns is even better, and you wouldn't even need to mock or stub the function, because you can just pass a fixed list to the sort function.

Upvotes: 3

Related Questions