Home > Back-end >  Is there a way to write something like this in Jest?
Is there a way to write something like this in Jest?

Time:10-08

I'm learning to test in React using Jest and Enzyme, and i keep having to repeat myself a lot and ending up with lengthy lines. In other words, is there a way to transform this:

describe('<CartItem />', () => {

  it('is a reusable component that renders cart items', () => {
    expect(shallow(<CartItem drilledProps={{ ...mockProps }} />)).toMatchSnapshot();
  });

  it('renders once', () => {
    expect(shallow(<CartItem drilledProps={{ ...mockProps }} />).length).toEqual(1);
  });

})

into this?

describe('<CartItem />', () => {

  const CartItem = <CartItem drilledProps={{ ...mockProps }} />;

  it('is a reusable component that renders cart items', () => {
    expect(shallow(CartItem).toMatchSnapshot());
  });

  it('renders once', () => {
    expect(shallow(CartItem).length).toEqual(1);
  });

})

CodePudding user response:

You could use a factory function:

describe('<CartItem />', () => {

  // Use factory function to dynamically create component.
  const CartItem = (mockProps) => <CartItem drilledProps={{ ...mockProps }} />;

  it('is a reusable component that renders cart items', () => {
    const mockProps = {...} // Whatever you need here.
    expect(shallow(CartItem(mockProps)).toMatchSnapshot());
  });
...
})
  • Related