0

我正在尝试测试react-lazy-load-image-component使用 JestJS 制作的惰性初始化组件。以下是我的测试:

const viewModel = new VehicleViewModel(vehicleData, {});

const mockOnClick = jest.fn();

const mockStore = configureStore();

let store: MockStore;

beforeEach(() => {
  jest.clearAllMocks();
  store = mockStore(storeInitialState);
});

describe('on component initialization', () => {
  it('renders', () => {
    const { container } = render(
      <Provider store={store}>
        <SearchResult vehicle={viewModel} onClick={mockOnClick} />
      </Provider>
    );
    expect(container).toMatchSnapshot();
  });
});

describe('when the user clicks on the result', () => {
  it('processes an onClick event', () => {
    const { container, getByTestId } = render(
      <Provider store={store}>
        <SearchResult vehicle={viewModel} onClick={mockOnClick} />
      </Provider>
    );
    await waitFor(() => {
      fireEvent.click(getByTestId('search-result'));
    });
    expect(container).toMatchSnapshot();
    expect(mockOnClick).toBeCalled();
  });
});

该组件编码为:

const SearchResult = ({ onClick, vehicle }: SearchResultProps): JSX.Element => {
  const {
    images,
    make,
    model,
    year,
    dealerName,
    city,
    state,
    timeOnMarket,
    mileage,
    price,
  } = vehicle;

  const monthlyPayment = useMonthlyPayment(price);

  return (
    <div className="search-result" data-testid="search-result" onClick={onClick}>
      <style jsx>{styles}</style>
      <div
        className="main-image"
        // replace multiple spaces, if any, with one
        title={`${year || ''} ${make || ''} ${model || ''} image`.replace(/  +/g, ' ')}
      >
        <Carousel images={images} year={year} make={make} model={model} />
        ...
    </div>
  );
};

<Carousel />渲染定义为:

  return (
    <LazyLoadComponent>
      <div
        className="carousel-container"
        onMouseEnter={handleMouseEnterEvent}
        onMouseLeave={handleMouseLeaveEvent}
      >
        ...
      </div>
    </LazyLoadComponent>
  );

没有延迟加载,我的测试工作正常。

延迟加载的包装器,我的测试失败了:TypeError: Cannot read property 'prototype' of undefined. 错误发生在const { container } = render(.... 我试图模拟滚动效果。还没有为我工作。

如何使用内部延迟加载向组件添加笑话覆盖?

4

2 回答 2

0

我最终在实际代码中执行了以下操作:

const TestLasyWrapper = ({ children }: any) => process.env.NODE_ENV !== 'test' ?
  <LazyLoadComponent>{children}</LazyLoadComponent> : 
    <>{children}</>;
于 2021-11-17T21:59:33.127 回答
-1

您必须“等待”您的组件被加载、安装和渲染。你在 Jest中使用React 测试库吗?如果是这样,您可以使用waitFor,它将轮询直到将项目添加到 DOM。

await waitFor(() => expect(screen.findByText('Foo')).toBeInTheDocument());
于 2021-11-16T12:20:01.560 回答