Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest + Enzyme testing if an element was focused to

Tags:

reactjs

jestjs

I want to test if an element is focused to when the component updated.

  componentDidUpdate() {
    this.button.focus();
  }

I have a render function which gets the component(s)

  function render(args) {
    const component = shallow(<MyComponent {...args} />);

    return {
      component,
      button: () => component.find("button"),
    };
  }

My assertion is as follows

describe("When component did update", () => {
  it("Should focus to the button", () => {
    const { component, button } = render(args);
    expect(button().focus).toHaveBeenCalled();
  });
});

With just this I get the error

Matcher error: received value must be a mock or spy function

So I thought I needed to add a mock of focus which I've now done in my beforeEach, and test that instead, which removes the error but my test asserts 0 calls instead of 1 call:

describe("When component did update", () => {
  it("Should focus to the button", () => {
    const { component, button } = render(defaultArgs);
    expect(backButtonElement.focus).toHaveBeenCalled();
  });
});

So I must be missing something else

like image 383
user1486133 Avatar asked Oct 20 '25 05:10

user1486133


1 Answers

This worked for me

const wrapper = mount(<MyComponent />);

const input = wrapper.find('input');

expect(input).toHaveFocus();
like image 107
VnoitKumar Avatar answered Oct 21 '25 20:10

VnoitKumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!