【发布时间】:2021-07-01 05:04:02
【问题描述】:
我有一个使用样式组件库设置样式的 HTML 按钮,我正在为它编写一个单元测试。 POC 代码如下所示:
const StyledButtonComponent = () => {
const [testText, setTestText] = React.useState();
const clickHandler = (e) => {
e.preventDefault();
setTestText('Lorem Ipsum')
console.log('Button Clicked!');
}
return (
<>
<TestButton onClick={clickHandler} data-test="component-styled-button">
Click Me!!
</TestButton>
<p data-test="text-tag">{testText}</p>
</>
);
}
这里的TestButton是一个样式化的组件。
而我的单元测试代码是:
describe('Styled Button Component', () => {
let wrapper;
const setup = () => mount(<StyledButtonComponent />)
const findByAttr = (wrapper, val) => {
return wrapper.find(`[data-test='${val}']`)
}
beforeEach(() => {
wrapper = setup();
});
it('should render the styled button component without errors', () => {
const btnComponent = findByAttr(wrapper, 'component-styled-button');
expect(btnComponent).toHaveLength(2);
});
it('should allow user to click on the styled button', () => {
const btnComponent = findByAttr(wrapper, 'component-styled-button');
btnComponent.simulate('click', { preventDefault() {}})
const pTag = findByAttr(wrapper, 'text-tag');
expect(pTag.render().text()).toBe('Lorem Ipsum')
});
});
但是对于第二个测试我得到一个错误:
方法“simulate”意味着在 1 个节点上运行。找到了 2 个。
那么测试使用 Styled Component 渲染的组件的正确方法是什么?
【问题讨论】:
-
你的
TestButton组件是什么样的? -
@slideshowp2 按钮的外观和感觉与我在按钮的样式化组件代码中提到的样式一致
标签: javascript reactjs unit-testing jestjs enzyme