0

I have created a function in my component. I want to know how can I write unit test cases for that function.

component code is -

const Test = () => {
   if(props.Test) {
     props.Test();
   }
}

my Test code is -

const Test =() => {
console.log("hi");
}

and then pass this Test function into my component. I am getting code coverage is not done in this function. So how to achieve code coverage for this function ?

I am passing a function named Test in this component. I need to check if I am getting this component in props then execute this function. So how Can I write unit test cases for this function in jest ?

1 Answer 1

1

First mock the function, for instance:

const mockTest = jest.fn();

Then pass it as a prop to your component, and test if it was called:

expect(mockTest).toHaveBeenCalled();

More on that: https://jestjs.io/docs/en/mock-functions.html

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

4 Comments

I am not sure what is this Test function, are you trying to mock it or use the original?
I am trying to it original. I have created a Test function in app.tsx file then passing this Test function in another component file.
Then you can spy on the function and then test if has been called.
How can I do that? Can you explain it ?

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.