document.getElementById(...)。getElementsByTagName不是函数

时间:2019-04-23 12:17:51

标签: reactjs jestjs enzyme

我正在尝试使用玩笑和酶进行测试,但我不断收到以下错误:

TypeError: document.getElementById(...).getElementsByTagName is not a function

或:

TypeError: Cannot read property 'getElementsByTagName' of null

componentDidUpdate(prevProps, prevState, snapshot) {
 var el = document.getElementById('myTable');
 var firstHeader =  document.getElementById('myTable').getElementsByTagName( 'thead' )[0].getElementsByTagName( 'tr' )[0].getElementsByTagName( 'th' )[0];

dragger.on('drop',(from, to, el) => {
 this.props.onHeaderDrop(
 document.getElementById('myTable').getElementsByTagName( 'thead' )[0].getElementsByTagName( 'tr' )[0].getElementsByClassName('handle')[from].getAttribute('id'),

我尝试在安装组件之前添加以下内容:

  const elementMock = { addEventListener: jest.fn() };
  jest.spyOn(document, 'getElementById').mockImplementation(() => elementMock);

或者我应该在道具上添加任何内容:this.props.onHeaderDrop吗?

1 个答案:

答案 0 :(得分:0)

尝试此操作...在文档之前添加窗口对象。

componentDidUpdate(prevProps, prevState, snapshot) {
 var el = window.document.getElementById('myTable');
 var firstHeader =  window.document.getElementById('myTable').getElementsByTagName( 'thead' )[0].getElementsByTagName( 'tr' )[0].getElementsByTagName( 'th' )[0];
}