【问题标题】:Why mock-function have not been called in test?为什么在测试中没有调用模拟函数?
【发布时间】:2019-09-17 06:40:47
【问题描述】:

我正在为一个组件编写测试。它有一个下载按钮。我想测试调用这个按钮的 onClick 函数。但它不起作用。我的测试出了什么问题?

describe('download-button tests', () => {
  let wrapper:any;
  let _download = jest.fn(()=>{console.log('That`s Submit-button function')});

  jest.mock('../components/CustomButtonComponent', ()=>
    <button className="download" data-test ="download_button" type="submit" name="Скачать" onClick={_download}/>);

  beforeAll(() => {
    let wrapper = setupmount();
    const nextState = {
      ...initialState,
      selectedEntity: "1864296",
      disableTable: false,
    };
    wrapper.setState(nextState);
    console.log(wrapper.debug());
    console.log(findByTestAttr(wrapper, 'download_button').first().debug());
    findByTestAttr(wrapper, 'download_button').first().simulate('click');
  });

  test('download-button is clicked', () => {
    expect(_download).toBeCalled();
  });
});

console.log(findByTestAttr(wrapper, 'download_button').first().debug());的结果:

https://sun9-10.userapi.com/c850124/v850124774/1ddcf0/_A7I6vHPHeM.jpg

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    我相信这是因为 onClick 侦听器附加到&lt;CustomButton/&gt; 的孩子,即&lt;button/&gt;。您是否尝试过将 data-test 道具传递给 &lt;button/&gt; 组件?否则尝试类似findByTestAttr(wrapper, 'download_button').first().childAt(0).simulate('click')

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多