0

I have the following onClick function

onClickFunction= index => () => {
  this.setState({ activeIndex: index });
}

Which is used in the following function

getPersons= (persons) => persons
  .map((person, index) => (
     <StyledComponentHeader
        key...
        ...
        onClick={this.onClickFunction(index)}
      >
        <Styled2
          ...
        >
          {person.name}
        </Styled2>
      </StyledComponentHeader>
    ))

in my unit test I need to test the onClickFunction. currently I have something like this

const component= (
  <StyledComponent
    persons={persons}
  />);

describe('...', () => {
  beforeEach(() => {
    wrapper = shallow(component);
});

it('testing name', () => {
  expect(wrapper).toMatchSnapshot();
  expect(wrapper.state().activeIndex).toEqual(0);
  wrapper.instance().onClickFunction(1);
  expect(wrapper.state().activeIndex).toEqual(1);
});

it returns saying that the above last except should be 0. What is the correct way to test this function?

2
  • Since onClickFunction does not change the state, but returns a function which if is called then changes the state, the logical way would be to test it with wrapper.instance().onClickFunction(1)() (notice the added () at the end to invoke the returned function) Commented Oct 26, 2018 at 21:25
  • 1
    Works like a charm, wasn’t a million miles off! Thanks! If you put it as an answer I’ll accept it :) Commented Oct 26, 2018 at 21:34

1 Answer 1

1

Since onClickFunction does not change the state, but returns a function which if called then changes the state, the logical way would be to test it with

wrapper.instance().onClickFunction(1)();

(notice the added () at the end to invoke the returned function)

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

Comments

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.