Sinon: Stubbing const objects

Created on 14 Apr 2015  路  5Comments  路  Source: sinonjs/sinon

Working in a node or es6 environment, many exported objects are defined as const, this is considered a good practice to avoid breaking modules of the application.

However - when testing, these const defined objects can't be stubbed out which seems problematic from a unit testing perspective.

I guess there's nothing that can happen from the perspective of Sinon to resolve this problem as it needs to mutate the target of stubbing/spying in order to change it in the test's context.

Are there any suggested approaches that could be used to somehow disable the behaviour of const imports/requires during test?

I've tried to stub/mock at import time but this doesn't seem to play nicely with build systems such as webpack/babel for numerous reasons so have settled with the regular sinon stubbing approach (which I also prefer) but I'm reluctant to change my exported objects to be mutable!

Question nodejiojs

Most helpful comment

For stubbing dependencies in node, I usually use one of these

Then you can redefine what the dependency is before loading your code.

These work really well for me. Are those the solutions you have tried?

All 5 comments

For stubbing dependencies in node, I usually use one of these

Then you can redefine what the dependency is before loading your code.

These work really well for me. Are those the solutions you have tried?

Have tried both. Webpack doesn't play nice as it doesn't use the node require directly.

Closest to a solution like this was to use the inject-loader plugin for webpack - this doesn't play well with babel loader.

This ticket is really a usage question, and not directly related to Sinon.JS either. Please post it to the ~Sinon.JS mailinglist~ Stack Overflow using the sinon tag, so the bigger community can help answer find a solution.

Thanks for this question and your answer. I searched sinon stub const and reached here, and your suggestion proxyquire solved my problem. If it's in the mailinglist, I think I can't find this answer in time.

rewire works wonderfully! Thanks!

Was this page helpful?
0 / 5 - 0 ratings