0

I'm trying to get into TDD, and a lot of examples sugests that we should use stubs to make our code more flexible. If I'm using javascript (for example) then why should I use stubs, since methods and even whole objects can be easily replaced for a mock?

Should I favor this:

const fetcher = require('some-async-lib');

function getData(url){
    return fetcher(url)
}

Or this

function getData(url, fetcher){
    return fetcher(url)
}

Imagine that I have some methods that use this fetcher, am I not polluting the code passing the fetcher everywhere?

1 Answers1

2

As @Robert pointed out in the comments it really depends on the system you are trying to build, there are hardly fit-all solutions.

As a rule of thumb if you have multiple kinds of fetchers (at least two) that can be used in the production code, the second approach would probably start to make sense. The more kind of fetchers you have, the more it is justifiable, according to my style of programming.

Instead, if you feel you're pushed towards the second solution only because you need to provide a mock in the test I would think about it twice. I always though that "writing coincise and reasonable code" and "writing fully testable code" are sometimes in my experience two aspects you should find a trade-off between. For instance I remeber once to be part of a project were full testability was our main goal, following the second approach we ended up with lot of classes with lot of dependecies. Newcomers in the project started to find hard to grasp the real meaning of all those dependencies. I must admit that in the other hand we could probably have managed the dependencies in a better way.

Anyhow, if your real problem in to mock the fetcher, you can give a look to mock-require. I never used it but it seems to me it does what you need in your example.

danidemi
  • 251
  • 1
  • 5