0

How can I test the return value for this function ?

handleValidatePassword = (confirmPassword) => {
    const { newPassword } = this.props;
    if (newPassword !== confirmPassword) {
      return <FormattedMessage id="some value" />;
    }
  }

I need to check if the returned value of this function is the expected one if condition is right:(FormattedMessage return span with value === id)

<span> some value </span>

i'm using shallow from enzyme for test

4
  • 2
    You should explain better what you want to do Commented Aug 2, 2019 at 12:02
  • Your question is a bit unclear. What are you using to render your component in the tests (Could it be enzyme?) Commented Aug 2, 2019 at 12:03
  • In function put console.log(changePass.alerts.notMatch); before return. Commented Aug 2, 2019 at 12:13
  • using import { shallow } from 'enzyme' for test Commented Aug 2, 2019 at 12:16

1 Answer 1

1

I would personally use enzyme-matchers if you use jest or jasmine f.e. https://github.com/FormidableLabs/enzyme-matchers/blob/master/packages/jest-enzyme/README.md#tocontainreact

import { shallow } from 'enzyme' 
import Element from './yourpath'

const wrapper = shallow(<Element />); // mount/render/shallow when applicable

//as shallow renders only one level of children components
expect(wrapper).toContainReact(<FormattedMessage id="some value" />);

//or if you want to test actually the span element you should use mount
const wrapper2 = mount(<Element />);
expect(wrapper).toContainReact(<span> some value </span>);
Sign up to request clarification or add additional context in comments.

7 Comments

does not work because <FormattedMessage> does not exist when the component is mounted, I have a condition inside the function, so I need to check that the function will return if the condition is met correctly, but thanks for this information, this will help me in the future. I need test just that function will return
For example -- ` wrapper.instance().handleValidatePassword = jest.fn(); wrapper.instance().handleValidatePassword.mockReturnValue(<span> changePass.alerts.notMatch </span>);` But this does not work to
Can you share component code where you are using this function? Is this condition in code depends on the state of component? If so then you can use setState in the tests f.e. like here
Can I verify that this function will return? As if it is independent of components and other things
or maybe I can somehow check if the condition works (example: newPassword !== confirmPassword)
|

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.