【问题标题】:getting 'NULL' error while I am testing 'document.getElementByID' line. I already tried attachTo approach but that is also not working在测试“document.getElementByID”行时出现“NULL”错误。我已经尝试过 attachTo 方法,但这也不起作用
【发布时间】:2019-12-03 11:45:50
【问题描述】:

我正在使用 jest 测试我的反应功能。在我测试时,我收到错误 focus of null for document.getElementById 行。

我已经尝试过这个解决方案。 jest + enzyme, using mount(), document.getElementById() returns null on component which appear after _method call 但这对我不起作用。

这是我的 abc.js

clearSearch = () => {
        const { typeSearchBox } = this.props;
        this.setState({ searchPlaceholderValue: PROMPTRAISED });
        this.setState({ searchValue: '' });
        this.setState({ showClearIcon: false });
        const searchBox = document.getElementById(`SearchBox_${typeSearchBox}`);
        searchBox.focus();
    };

这是我的 abc.test.js

it('+++ inputs valid filtered search text', () => {
     categoryWrapper.find('ClearIcon').prop('onClick')();
});

点击 clearIcon clearseach 时触发。

【问题讨论】:

  • 请添加测试文件中的代码。

标签: reactjs jestjs enzyme jsdom


【解决方案1】:

您需要模拟document.getElementById 函数以在您的测试文件中返回一个带有focus 函数的对象。

const mockUpObject = {
  focus: () => null,
};
global.document.getElementById = jest.fn(() => mockUpObject);

【讨论】:

  • 我们可以为 blur 做同样的事情吗? searchBox.blur();
  • 是的,我们可以。您可以在 mockUpObject 中添加模糊功能
猜你喜欢
  • 1970-01-01
  • 2020-07-31
  • 2023-03-14
  • 2022-08-04
  • 2022-09-23
  • 1970-01-01
  • 2012-05-26
  • 1970-01-01
  • 2018-12-07
相关资源
最近更新 更多