Skip to content
Advertisement

Mocking methods of a JavaScript object created within a function

I’ve written a JavaScript function that creates an object from a require()’d library, and then uses it. That seems to be causing me trouble when I try to write tests for it because I don’t seem to have a good way to gain control over that object and create mocks of its methods to test the behavior of my function.

Am I running into this because I’ve designed the function poorly? I come from a Java/Spring background, so the voices in my head are screaming “dependency injection”. Is there’s a better way to do that than just passing the object my function needs into it as a parameter?

Example function:

JavaScript

I start running into jams when I try to write tests to verify my function’s behavior when dynamo.get() returns successfully or throws an error.

Example test (I’ve been using Sinon for mocking and Chai for asserting):

JavaScript

It seems obvious that the mock of dynamo.get() I’ve created doesn’t get used by dbService.getItem() because dbService.getItem() completely owns the instantiation of its own dependency on a DocumentClient object.

Should I just pass a DocumentClient into my getItem() function, or is there a better way?

Advertisement

Answer

DI is the best way, it will make your code easier to test, better scalability, and decouple the modules. But you still can stub the aws-sdk module if you want to require the module as the dependency. Unit test solution:

dbService.js:

JavaScript

dbService.test.js:

JavaScript

unit test result:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement