【问题标题】:Is there a way to write something like this in Jest?有没有办法在 Jest 中写这样的东西?
【发布时间】:2021-10-08 04:22:47
【问题描述】:

我正在学习使用 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);
  });

})

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案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());
      });
    ...
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-01
      • 2015-02-02
      • 2013-07-30
      • 2014-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多