Quantcast
Channel: Testing React component with Enzyme Jest finding HTML element - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Testing React component with Enzyme Jest finding HTML element

$
0
0

I have a component called Typography that takes a variant prop and renders an element accordingly.

Typography.js

Omitting a lot for brevity

import { StyledH1, ... } from './Typography.styles';

const variantMapping = {h1: StyledH1, ...};

const Typography = ({ children, ...props }) => {
  const Component = variantMapping[props.variant] ? variantMapping[props.variant] : 'span';

  return <Component {...props}>{children}</Component>;
};

So I've tried numerous ways to get a working test. Right now I'm trying to pass variant="h1", get back the following markup <h1 class="..styled component what nots...">...</h1> and verify an <h1> renders

Typography.spec.js

import { mount } from 'enzyme';
import Typography from '.';

describe('<Typography />', () => {
  it('renders H1', () => {
    const wrapper = mount(<Typography variant="h1" />);
    const elem = wrapper;
    console.log(elem.debug());
    expect(wrapper.find('h1')).toEqual(true);
  });
});

So running the debugger I get back

console.log components/Typography/Typography.spec.js:9
    <Typography variant="h1" bold={false} transform={{...}} small={false}>
      <Typographystyles__StyledH1 variant="h1" bold={false} transform={{...}} small={false}>
        <StyledComponent variant="h1" bold={false} transform={{...}} small={false} forwardedComponent={{...}} forwardedRef={{...}}>
          <h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />
        </StyledComponent>
      </Typographystyles__StyledH1>
    </Typography>

So I changed up the element variable to find the h1 element const elem = wrapper.find('h1');

And debugger returns

console.log components/Typography/Typography.spec.js:9
<h1 transform={{...}} className="Typographystyles__StyledH1-sc-1n6ui1k-0 bvGdAG" />

I'm not sure if this is the right approach, just a matter of trying to get at least 1 reasonably passing test.

At this point every expect statement I write comes back with an error or failure

  • expect(elem).to.have.lengthOf(1); TypeError: Cannot read property 'have' of undefined
  • expect(elem.contains('h1')).to.equal(true); TypeError: Cannot read property 'equal' of undefined
  • expect(elem.contains('h1')).toEqual(true); expect(received).toEqual(expected) // deep equality

Have tried a few more options and nothing is working out. Any help would be greatly appreciated.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>