简体   繁体   English

模拟点击样式组件测试

[英]Simulating click on a styled component tests

I have a styled Button:我有一个样式按钮:

const MyButton = styled.button`...`

And I render it with an onClick prop:我用一个onClick道具渲染它:

<MyButton onClick={props.onClick}>A Button</MyButton>

In my tests files for the button I use Enzyme to test the onClick (the styled button is imported as 'button'):在我的按钮测试文件中,我使用酶来测试onClick (样式按钮被导入为“按钮”):

let counter = 0;
const component = shallow(
     <Button onClick={() => counter++}>
          A Button
     </Button>
);
component.find(Button).simulate('click');

In the console I get: Method “simulate” is meant to be run on 1 node. 0 found instead.在控制台中我得到: Method “simulate” is meant to be run on 1 node. 0 found instead. Method “simulate” is meant to be run on 1 node. 0 found instead.

When debugging using component.debug() I see the element is <styled.button>...</styled.button> I tried changing my find() to receive styled.button and even adding a class name which I can see when debugging but nothing seems to get the element.使用component.debug()调试时,我看到元素是<styled.button>...</styled.button>我尝试将find()更改为接收styled.button ,甚至添加一个我可以在何时看到的类名调试但似乎没有得到元素。

How can I find the element and simulate events on it?如何找到元素并在其上模拟事件? Thank you谢谢

With component.find(Button) you're trying to find a button inside a button which is not the case in your example.使用component.find(Button)您试图在按钮内找到一个按钮,这在您的示例中并非如此。 Just go for:去吧:

let counter = 0;
const component = shallow(
     <Button onClick={() => counter++}>
          A Button
     </Button>
);
component.simulate('click');

If you are testing MyButton then you should import it, and use it:如果您正在测试 MyButton,那么您应该导入它并使用它:

import MyButton from './some-button';
const component = shallow(<MyButton />);
component.find(MyButton).simulate('click');

You are however, using which you're not importing, or using in the real code?但是,您是在使用未导入的还是在实际代码中使用的?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM