首页 > 解决方案 > React - 使用 Jest 进行前端组件测试

问题描述

我刚刚为我的组件编写了测试文件,目前它非常初级。我对前端的笔试非常缺乏经验。我对这个测试文件运行了纱线测试,但它失败了。

这是消息:

无法找到带有文本的元素:请查看您的帐单详细信息...

在此处输入图像描述

这是我到目前为止的测试:

import React from 'react';
import { render, cleanup, waitForElement } from 'react-testing-library';

// React Router
import { MemoryRouter, Route } from "react-router";

import Show from './Show';


test('it shows the offer', async () => {

  const { getByText } = render(
      <MemoryRouter initialEntries={['/booking-requests/20-A1-C2/offer']}>
        <Route
          path="/booking-requests/:booking_request/offer"
          render={props => (
            <Show {...props} />
          )}
        />
      </MemoryRouter>
  );

  //displays the review prompt
  await waitForElement(() => getByText('Please review your billing details, contract preview and Additions for your space. Once you’re happy, accept your offer'));

//displays the confirm button
 await waitForElement(() => getByText('Confirm'));
});

这是组件:

// @flow
import * as React from 'react';
import i18n from 'utils/i18n/i18n';
import { Btn } from '@appearhere/bloom';
import css from './Show.css';
import StepContainer from 'components/Layout/DynamicStepContainer/DynamicStepContainer';

const t = i18n.withPrefix('client.apps.offers.show');

const confirmOfferSteps = [
  {
    title: t('title'),
    breadcrumb: t('breadcrumb'),
  },
  {
    title: i18n.t('client.apps.offers.billing_information.title'),
    breadcrumb: i18n.t('client.apps.offers.billing_information.breadcrumb'),
  },
  {
    title: i18n.t('client.apps.offers.confirm_pay.title'),
    breadcrumb: i18n.t('client.apps.offers.confirm_pay.breadcrumb'),
  },
];

class Show extends React.Component<Props> {
  steps = confirmOfferSteps;

  renderCtaButton = (): React.Element<'Btn'> => {
    const cta = t('cta');

    return <Btn className={css.button} context='primary'>
      {cta}
    </Btn>
  };

  renderLeftContent = ({ isMobile }: { isMobile: boolean }): React.Element<'div'> => (
    <div>
      <p>{t('blurb')}</p>

      {!isMobile && this.renderCtaButton()}
    </div>
  );

  renderRightContent = () => {
    return <div>Right content</div>;
  };

  render() {
    const ctaButton = this.renderCtaButton();

    return (
      <StepContainer
      steps={this.steps}
      currentStep={1}
      ctaButton={ctaButton}
      leftContent={this.renderLeftContent}
      rightContent={this.renderRightContent}
      footer={ctaButton}
    />
    );
  }
}

export default Show;

我错过了什么?建议将其他内容添加到我的测试文件中,将不胜感激!

标签: reactjstestingjestjs

解决方案


推荐阅读