Javascript 你能把一个模拟的“文档”传递给一个笑话包装器吗?

Javascript 你能把一个模拟的“文档”传递给一个笑话包装器吗?,javascript,reactjs,dom,jestjs,enzyme,Javascript,Reactjs,Dom,Jestjs,Enzyme,我目前有一个组件,单击按钮后,该组件的ID将使用document.getElementByID.setAttribute进行更新。我正在编写单元测试,需要模拟document.getelementId。问题是我不知道如何在包装器中通过这个模拟,以便在测试中使用它 我正在尝试测试的组件: const Component = (props) => { const {data} = props; const { url, title } = data;

我目前有一个组件,单击按钮后,该组件的ID将使用document.getElementByID.setAttribute进行更新。我正在编写单元测试,需要模拟document.getelementId。问题是我不知道如何在包装器中通过这个模拟,以便在测试中使用它

我正在尝试测试的组件:

const Component = (props) => {
   const {data} = props;
   const {
     url,
     title
   } = data;

   const handleClick = () => {
    document.getElementById('NotDismissed').setAttribute('id', 'Dismissed');
  };

  return (
     <div id='NotDismissed'>
       <a href={url}>{title}</a>
       <button
         onClick={() => handleClick()}
         className='closeButton'
       />
     </div>
  );

};

Component.propTypes= {
  data: PropTypes.object.isRequired;
}

export default Component;


有人能帮我弄清楚如何在组件内传递mockDoc以便使用吗?

document
是一个全球性的笑话。您可以访问覆盖或模拟其属性,如下所示:

global.document.getElementById=spyFunc;

const spyFunc=jest.spyOn(global.document,'getElementById');
如果您收到有关
setAttribute
的错误,可能是由于您的模拟没有该属性造成的。您可以用类似的方式模拟功能:

const fakeSetAttribute=jest.fn();
const fakeGetElementById=jest.fn().mockImplementation((id)=>{
返回{
setAttribute:fakeSetAttribute
}
});
global.document.getElementById=fakeGetElementById;

Hm,我明白你的意思,但问题是我仍然不知道如何将spyFunc或global.document.getElementById传递到包装器本身?在最初的帖子中,我认为使用属性文档和设置spyFunc会有所帮助,但我仍然收到与以前相同的错误@James@C.Lewis你能发布你要测试的代码吗?这可能是因为
文档
没有被定义为一个全局文件,我用我试图测试的组件的主要部分更新了我的问题@James@C.Lewis我添加了一个模仿SetAttributeEyeah的例子,这很有效!!!非常感谢你!我真的很感激@詹姆斯
    const spyFunc = jest.fn();
    const mockDoc = Object.defineProperty(document, 'getElementById', { value: spyFunc });

    const wrapper = mount(
      <Provider store={store}>
        <Component
          data={mockValidData}
          document={mockDoc}
        />
      </Provider>
    );
    expect(spyFunc).not.toHaveBeenCalled();
    wrapper.find('button.closeButton').simulate('click');
    expect(spyFunc).toHaveBeenCalled();
Error: Uncaught [TypeError: Cannot read property 'setAttribute' of undefined]