Reactjs 呈现测试中具有document.getElementById的组件
如何模拟document.getElementByIdReactjs 呈现测试中具有document.getElementById的组件,reactjs,jestjs,enzyme,Reactjs,Jestjs,Enzyme,如何模拟document.getElementById TypeError: Cannot read property 'style' of null 68 | 69 | componentDidMount() { > 70 | document.getElementById('main').style.backgroundImage = "./images/background1.png"; | ^ 7
TypeError: Cannot read property 'style' of null
68 |
69 | componentDidMount() {
> 70 | document.getElementById('main').style.backgroundImage = "./images/background1.png";
| ^
71 | document.getElementById('main').style.backgroundSize = 'auto';
72 | }
我试着嘲笑他
const dummyElement = document.getElementById('main');
const style = {backgroundImage:"", backgroundSize:""}
const elem= jest.fn()
const getElementById = (elem)=>jest.fn()
我正在尝试运行的简单测试
it('render with props', ()=>{
const wrapper = shallow(<Login />);
})
it('render with props',()=>{
常量包装器=浅();
})
我只想渲染组件请尝试以下操作:
jest.spyOn(document, 'getElementById').mockImplementation(() => document.createElement('div'));
这应该可以为您解决问题。类似jest.spyOn(document,'getElementById').mockImplementation(()=>document.createElement('div'))的东西;谢谢你的快速解决方案,它成功了。把它写下来作为答案,这样我就可以接受了。非常感谢你的解答。这节省了我的时间。