React快照玩笑测试,条件渲染

发布于 2025-02-10 01:28:56 字数 1172 浏览 0 评论 0原文

我是开玩笑的新手,一般来说,我正在为React代码编写开玩笑的快照测试。代码渲染具有相应属性的链接组件,如果存在HREF,则链接组件。如何为其编写快照? 该代码很漫长,但这是有条件的渲染部分:

<Typography
        variant="h4"
        component="h1"
        gutterBottom
      >
        {serverPublicationResponse?.title}
        { externalLink && (
          <Link
            target="_blank"
            underline="hover"
            aria-label={serverPublicationResponse?.title}
            href={serverPublicationResponse?.doiLink}
          >
            <Launch sx={{ fontSize: '1.75rem', ml: 0.35 }} />
          </Link>
        )}
      </Typography>

这是迄今为止的开玩笑测试,有没有一种方法可以在一个测试中写整个快照测试?

describe('pagePublication', () => {
  test('should match with the previous snapshot', (done) => {
    const x: Publication = { key: '', title: '', year: 1 };
    const y: PublicationKeyphrase = { keyphrases: [] };
    const testRenderer = TestRenderer.create(
      <PagePublication
        serverPublicationResponse={x}
        serverPublicationKeyphraseResponse={y}
      />,
    );
    expect(testRenderer.toJSON()).toMatchSnapshot();
    done();
  });
});

I am new to Jest and testing in general, I am writing a Jest snapshot testing for a react code. The code renders Link component with corresponding attributes, and an Icon if an href exists.How can I write the snapshot for it?
The code is lengthy, but This is the conditional rendering part:

<Typography
        variant="h4"
        component="h1"
        gutterBottom
      >
        {serverPublicationResponse?.title}
        { externalLink && (
          <Link
            target="_blank"
            underline="hover"
            aria-label={serverPublicationResponse?.title}
            href={serverPublicationResponse?.doiLink}
          >
            <Launch sx={{ fontSize: '1.75rem', ml: 0.35 }} />
          </Link>
        )}
      </Typography>

And this is the Jest test so far, Is there a way I can write the whole snapshot test in just one block of test?:

describe('pagePublication', () => {
  test('should match with the previous snapshot', (done) => {
    const x: Publication = { key: '', title: '', year: 1 };
    const y: PublicationKeyphrase = { keyphrases: [] };
    const testRenderer = TestRenderer.create(
      <PagePublication
        serverPublicationResponse={x}
        serverPublicationKeyphraseResponse={y}
      />,
    );
    expect(testRenderer.toJSON()).toMatchSnapshot();
    done();
  });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文