【问题标题】:unit testing styled component in react单元测试风格的组件反应
【发布时间】: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


【解决方案1】:

当你在 EnzymeJS 的包装器中找到时,它会给你返回实际的 DOM 元素以及包装它的 React Wrapper。

要解决此问题,您可以使用多个选项。 其中之一是first()

const btnComponent = findByAttr(wrapper, 'component-styled-button').first();

参考:https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/first.html

另一个是at(index)

const btnComponent = findByAttr(wrapper, 'component-styled-button').at(0);

参考:https://enzymejs.github.io/enzyme/docs/api/ReactWrapper/at.html

【讨论】:

  • 感谢@Kevin 的回答。我相信当我用 标签包装我的组件以防 redux
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
  • 1970-01-01
  • 2018-03-23
  • 1970-01-01
  • 2017-09-24
  • 1970-01-01
  • 2015-06-28
相关资源
最近更新 更多