1

Suppose we have a functional component as below.

const Test: React.FC = () => {

  const isItemSelected = () => { console.log('Hi); };

  return (
  <div> </div>
  );
};

And I want to invoke isItemSelected function directly while writing unit test without simulating any click or change event. Is it possible ?

1 Answer 1

0

One way to easily do this, without using any additional frameworks for testing, is to take your business logic and keep it separate from the actual React Components, so in your case you could define your function as such:

const isItemSelected = () => { console.log('Hi'); };
const Test: React.FC = () => {

  return (
  <div> </div>
  );
};

Now you can write simple unit tests for isItemSelected. If you have dependencies in your function to let's say a 'setState', you can just pass that as an argument to your function. But be careful, if you don't actually have any logic, then you are trying to unit test UI, which is generally not needed, that might be a testing anti pattern.

Also see: http://blog.codepipes.com/testing/software-testing-antipatterns.html

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Ali, no I need to keep that function inside React component.
you really don't, if you want you can post a full example
Actually that function I want to test is passed as a props to another Component and from there this function is triggered. We cannot modify the design now. We need to improve the code coverage so we are writing unit test now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.