使用 Enzyme 收听 onClick

我想断言当一个禁用的按钮被点击时,它的onClick事件不会被触发。我如何用酶来做到这一点?请参阅下面的示例代码。谢谢!


示例按钮.jsx:


import React from 'react';


const SampleButton = () => (

  <button

    disabled={true}

    onClick={() => console.log('You clicked me!')}

    test-attr="button"

    type="button"

  >

    Click Me

  </button>

);


export default SampleButton;

sampleButton.test.jsx:


import React from 'react';

import { shallow } from 'enzyme';

import SampleButton from './sampleButton';


test('cannot click button if disabled', () => {

  const wrapper = shallow(<SampleButton />);

  const button = wrapper.find('[test-attr="button"]');

  button.simulate('click');

  // assert that `onClick` has not been fired

});


慕斯709654
浏览 195回答 1
1回答

呼啦一阵风

真的没有必要测试这个。该disabled道具是底层的HTML的一部分,所以通过测试它只是测试的HTMLbutton作品(你可以相信它)。更好的测试可能是检查disabled道具是否true在您尝试测试的条件下设置。也就是说,一种方法是将您的onClick注入SampleButtonvia props,如下所示:const SampleButton = ({ onClick }) => (&nbsp; <button&nbsp; &nbsp; disabled={true}&nbsp; &nbsp; onClick={onClick}&nbsp; &nbsp; test-attr="button"&nbsp; &nbsp; type="button"&nbsp; >&nbsp; &nbsp; Click Me&nbsp; </button>);然后你可以像这样测试它:test('cannot click button if disabled', () => {&nbsp; // Set up a mock function that allows you to make assertions&nbsp; const mockOnClick = jest.fn();&nbsp; // Pass it into SampleButton&nbsp; const wrapper = shallow(<SampleButton onClick={mockOnClick} />);&nbsp; const button = wrapper.find('[test-attr="button"]');&nbsp; button.simulate('click');&nbsp; // Make assertions&nbsp; expect(mockOnClick).not.toHaveBeenCalled();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript