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
This worked for me
const wrapper = mount(<MyComponent />);
const input = wrapper.find('input');
expect(input).toHaveFocus();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With