Jest Snapshot Tests 📸

For Styled Components

The Problem

Limitations of common test utils

import styled from 'styled-components';

const Button = styled.button`
  background-color: #7D7D7D;
  color: #FFF;
`;

export default Button;
describe('Button Component', () => {
  it('renders a button element', () => {
    const wrapper = shallow(Button);
    // this test is basically worthless
    expect(wrapper).toBeA('button');
  });
});

The Solution

Snapshots to the rescue

import styled from 'styled-components';

const Button = styled.button`
  background-color: #7D7D7D;
  color: #FFF;
`;

export default Button;
describe('Button Block', () => {
  it('renders correctly', () => {
    const tree = renderer
    .create(<Button>Submit</Button>)
    .toJSON();
    expect(tree).toMatchSnapshot();
  });
});

A Live Example

Hold on to your butts

Other Tips

• Snapshots are not TDD

• Keep snapshots small

• Use a test:watch script

• Understand failures

• Track test coverage

• Snapshots + CI

Thanks! ✌️📸

Hi, I'm Alan! 👋

deck

By Alan Smith

deck

  • 265