Antarktis
Antarktis

Reputation: 163

Mock function is not called with on click method with enzyme

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".

Upvotes: 0

Views: 115

Answers (1)

Kuldeep Bhimte
Kuldeep Bhimte

Reputation: 959

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.

Upvotes: 1

Related Questions