你能把一个模拟的 "文档 "传入Jest Wrapper吗?

问题描述 投票:0回答:1

我目前有一个组件,当点击一个按钮时,组件的ID会使用document.getElementByID.setAttribute更新。我正在编写单元测试,我需要模拟document.getelementId。问题是我不知道如何在包装器中传递这个mock,以便在测试中使用它。

我正在测试的组件。

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;

我当前的测试

    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]

有谁能帮我弄清楚如何在组件中传递mockDoc,使其能够被使用?

javascript reactjs dom enzyme jest
1个回答
1
投票

document 是Jest中的一个全局。你可以像这样访问覆盖或模拟它的属性。

global.document.getElementById = spyFunc;

或者

const spyFunc = jest.spyOn(global.document, 'getElementById');

如果你收到一个关于 setAttribute这可能是由于你的mock没有这个属性造成的。你可以用类似的方式来模拟该功能。

const fakeSetAttribute = jest.fn();
const fakeGetElementById = jest.fn().mockImplementation((id)=> {
  return {
    setAttribute: fakeSetAttribute
  }
});

global.document.getElementById = fakeGetElementById;
© www.soinside.com 2019 - 2024. All rights reserved.