【问题标题】:How to get style attribute of DOM node using Jest?如何使用 Jest 获取 DOM 节点的样式属性?
【发布时间】:2018-02-19 23:25:39
【问题描述】:

我有以下组件:

// Styled component.
export const StyledBtn = styled.button`
    height: ${( height ) => height};
`;

// Functional component.
const Btn = ({ height }) => <StyledBtn height={height} />;

export default Btn;

我希望能够检查实际高度(在 DOM 中)是否是传递给 Btn 组件的高度(我不想检查 prop 值)。这就是我设想的测试外观:

test('button renders at the correct height', () => {
    const btn = mount(<Btn height={20});
    const node = findDOMNode(btn);
    const height = node.getAttribute('height');
    expect(height).toEqual('20');
});

但是,测试失败了:

expect(received).toEqual(expected)

    Expected value to equal:
      "20"
    Received:
      null

任何想法如何测试这个?

【问题讨论】:

  • 我认为Btn 的代码是错误的。您将道具传递给 height 属性。应该是:const Btn = props =&gt; &lt;StyledBtn height={props.height} /&gt;;
  • 是的,对不起,我的错误我已经编辑了问题以显示正确的语法。使用正确的代码问题仍然存在。
  • 有没有像 Enzyme 那样的 .props() 函数?如果是这样,你可以这样做.props().style
  • 试过btn.find('button').props().style,但这是undefined

标签: reactjs jestjs styled-components


【解决方案1】:

使用库jest-styled-components。此外,mount() 函数正在安装功能组件,因此您需要在其中 find 样式化组件:

import 'jest-styled-components';
...
test('button renders at the correct height', () => {
    const component = mount(<Btn height={20});
    const btn = component.find('button');
    expect(btn).toHaveStyleRule('height', '20px');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-06
    • 2011-01-24
    • 2012-10-28
    • 2023-03-10
    • 1970-01-01
    • 2013-10-21
    • 2022-07-01
    • 1970-01-01
    相关资源
    最近更新 更多