有没有办法在 Jest 中写这样的东西?

Is there a way to write something like this in Jest?

我正在学习使用 Jest 和 Enzyme 在 React 中进行测试,而且我一直不得不重复很多次,最后以冗长的行结束。换句话说,有没有办法改变这个:

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

})

进入这个?

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

})

您可以使用工厂函数:

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());
  });
...
})