Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is exporting a function just for testing considered a bad practice?

I have this question especially after reading the official redux documentation on testing React components:

https://github.com/reduxjs/redux/blob/master/docs/recipes/WritingTests.md

In order to be able to test the App component itself without having to deal with the decorator, we recommend you to also export the undecorated component

Even the famous https://www.reactboilerplate.com/ exports named unconnected components just to be able to test them without mocking a store.

But isn't it considered bad to export something just so it makes things easier to test?

There might be cases when a developer makes the wrong import and introduces a bug just because there are two things exported from a file.

So, the question essentially is:

Can we make changes to the actual code to make testing easier?

Although this question is specific to React, would be great to know if any other languages or frameworks have similar problems and how they are dealt with.

like image 477
Faizuddin Mohammed Avatar asked Jun 28 '19 05:06

Faizuddin Mohammed


People also ask

How do you test a function without exporting it?

Testing the non-exported function by testing the function(s) that use it is not really unit-testing. I agree that "private functions are an implementation detail" and it's not them that they need to be tested, but the behaviour of your publicly available function, class or whatever you have at hand.

Is export default bad practice?

From my experience using default exports is error-prone solution because you don't know whether a specific piece of code exists in a file. When I'm using named exports my code editor can early spot errors by checking whether an imported component exists in a source file.


1 Answers

you can always do conditional export based on your environment.

something like:

export default connect(mstp, mdtp)(component1);

export let tests = {
  component1,
  component2,
  ...
};

if (process.env.NODE_ENV !==   "test") {
  tests = undefined;
}

and then in your test file you do

import { tests} from ".";
const { component1, component2 } = tests;
//now test unconnected components
like image 101
dee zg Avatar answered Oct 18 '22 09:10

dee zg