0

I'm trying to just test that a function is indeed invoked when a click action occurs on a link in my component. I keep receiving the error Expected mock function to have been called, but it was not called. But it works correctly in the browser.

I thought maybe there was an issue with the test finding the id I was asking it to look for, but using other methods I see it was able to access the element just fine.

The component

import { toggleEditMode } from './otherFile.js'
class PersonalInformation extends Component {
  constructor(props) {
    super(props);
    this.state = {editMode: false}
    this.toggleEditMode = toggleEditMode.bind(this);
  }

  render(){
   const { editMode } = this.state;
   return(
     <div>
{!editMode &&
            <div className="col-md-4 hidden-sm-down">
              <a
                id="editingToggleButton"
                className="display-block"
                role="button"
                href="javascript:void(0);"
                onClick={() => this.toggleEditMode()}
              >
                <span className="icon icon-sm dls-icon-edit" />
                <span className="pad-1-l">Edit</span>
              </a>
            </div>
          }
     </div>
)
}
}

The toggleEdit method

export function toggleEditMode() {
  this.setState({ editMode: !this.state.editMode })
}

The test

describe('edit', () => {
  it('should switch to editMode with click', () => {
  const toggleEditMode = jest.fn();
  const wrapper = mount(
    <PersonalInformation
      toggleEditMode={toggleEditMode}
    />
  );
    wrapper.find('#editingToggleButton').simulate('click');
    expect(toggleEditMode).toHaveBeenCalled();
});
}

I was able to log what it finds when using the find method and it returns the right element. But I can't seem to figure out how "it was not called".

1 Answer 1

1

In the test file you have assigned the mock function to the props but in the component you are using it as a class function.

So, in the test file, when the user clicks the HTML element it fires the class function and not the mocked one.

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

3 Comments

Ah that makes sense, though now I'm running into a different error of TypeError: Cannot read property 'setState' of undefined, referring to when the function tries to change the state. I tried adding ` wrapper.setState({editMode: false})` before wrapper.find, but it doesn't seem to help :(
Shouldn't be the case though, as you have declared wrapper
That's what I thought, and the function is bound to the component as well.

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.