How can I test styled components?

Viewed 3662

What I need to test is LoginWrapper always renders inside Login component. I test it as follow but it does not pass since LoginWrapper cannot be found.

  import React from 'react';
  import Login from '../components/Login';

  import Wrapper from '../components/Wrapper';
  import styled from 'styled-components';

  describe('test login', () => {

    const shallowRender = (props) => shallow(<Login {...props} />);
    let LoginWrapper;

    beforeEach(() => {
      LoginWrapper = styled(Wrapper)``;
    });

    afterEach(() => {
    });

    it('always render LoginWrapper', () => {
      const login = shallowRender({
        onSubmit: () => {}
      });
      const divs = login.find(LoginWrapper);
      expect(divs).toHaveLength(1);
    });

  });

Login.js

  import React from 'react';
  import Wrapper from './Wrapper';
  import { H5, Text, ALink } from '@lendi/lendi-components';
  import styled from 'styled-components';

  const LoginWrapper = styled(Wrapper)`
    .mobile {
      margin-bottom: 2px;
    }
    .signup {
      padding-left: 5px;
    }
  `;

  function Login ({onSubmit}) {
      return (
        <LoginWrapper>
          <H5 style={style.center}>
            {txt.title}
          </H5>
        </LoginWrapper>
        );
    }

export default Login;

It appears LoginWrapper will be rendered like <Styled(styled.div)> then what is the correct way to find it?

Any advice will be appreciated.

1 Answers

You can try setting LoginWrapper display name to LoginWrapper using this:

LoginWrapper.displayName = 'LoginWrapper'

to override the display name of your component. This is due to Style Component is a HOC and your component name will change if you wrapped your component with it.

Another thing is you need to delete these lines in your test case as it doesn't help:

let LoginWrapper;

beforeEach(() => {
  LoginWrapper = styled(Wrapper)``;
});

afterEach(() => {
});

and change the following your find from const divs = login.find(LoginWrapper); to a string like this const divs = login.find('LoginWrapper');

I hope this help!

Related