How to get style attribute of DOM node using Jest?

1.8k Views Asked by At

I have the following component:

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

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

export default Btn;

I want to be able to check that the actual height (in the DOM) is what was passed to the Btn component (I do not want to check the prop value). This is how I would envisage the test looking:

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');
});

But, the test fails:

expect(received).toEqual(expected)

    Expected value to equal:
      "20"
    Received:
      null

Any ideas how to test this?

1

There are 1 best solutions below

0
On

Use the library jest-styled-components. Also, the mount() function is mounting the functional component, so you then need to find the styled component within it:

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');
});