1
votes

I'm trying to come up with a way to test a component method that makes use of a helper function, like so:

handleUserClick = e => {
  this.setState({ somePieceOfState: e.target.value }, () => {
    someHelperFn(e.target.value);
  });
}

This is a bit of a crude example, but basically right now I have code coverage (Jest) for the entire component except the line where the helper function is being called. I don't see how importing the helper function separately into the test file could help either, so I'm stumped.

EDIT: I'm asking this as a broad question for how to test components that make use of helper functions or functions that are not component methods, not specifically for that^ example above.

Upon request, here is a closer look at the function being called:

const someHelperFn = params => {
  const BASE_URL = '/api/public/log-client-event';
  const queryString = generateQueryString(params);
  const logClientRequest = new XMLHttpRequest();
  logClientRequest.open('GET', `${BASE_URL}${queryString}`);
  logClientRequest.send();
  return logClientRequest;
};

It is not returning a value. It just seems like Jest is complaining because it exists within the React component and there's no way to actually test it (that I know of).

1
Sounds like your tests might exit before that callback runs. You could initially just try adding a delay into your testing code, to see whether this was the case. - Dan Prince
@DanPrince He's asking how to test helper functions in general I think, not as just a callback. - Martin Dawson
Why does it matter that it's a helper function? Just test the return value of it is what you expect. Kind of hard to know what you want with this minimal code example As it's a helper function you can also test it separately in another dedicated test for helpers. - Martin Dawson
@MartinDawson You're right. Right now I'm looking into excluding that function call with istanbul since Jest uses istanbul underneath the hood. Problem is istanbul kind of sucks at selectively turning off certain parts of code. - Jose
@MartinDawson The helper function (in my case) is not returning a value, just making a request to track user interactions. - Jose

1 Answers

1
votes

In this example you provided you would mock out XMLHttpRequest. You would then test that it's been called when handleUserClick is called. It depends on what the helper function is doing to how you can test it but their is almost certainly a way.

Istanbul (not jest) is complaining because you have no test that is actually executing the function I imagine so it marks it as not covered by any test.

It's really too broad of question to get a definitive answer for testing all helper functions.

Edit:

If you must test the helper function and can't test it internally like I did above then you can use proxyQuire as a last resort to mock the helper function out into a spy and then check that it was called. I wouldn't do this as default though because it can get messy.