玩笑 + 酶测试是否关注某个元素

use*_*133 4 reactjs jestjs

我想测试组件更新时元素是否聚焦。

  componentDidUpdate() {
    this.button.focus();
  }
Run Code Online (Sandbox Code Playgroud)

我有一个获取组件的渲染函数

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

    return {
      component,
      button: () => component.find("button"),
    };
  }
Run Code Online (Sandbox Code Playgroud)

我的断言如下

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

仅此我就得到了错误

匹配器错误:接收到的值必须是模拟或间谍函数

所以我想我需要添加一个focus我现在在我的中完成的模拟beforeEach,并对其进行测试,这会消除错误,但我的测试断言0 calls而不是1 call

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

所以我一定还缺少其他东西

Vno*_*mar 5

这对我有用

const wrapper = mount(<MyComponent />);

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

expect(input).toHaveFocus();
Run Code Online (Sandbox Code Playgroud)