如何用 Jest 解析 "serializes to the same string" 消息?

How to resolve "serializes to the same string" message with Jest?

在我的 React 应用程序中,我构建了一个函数,它接受一个充满常规文本的字符串和任意数量的 URL。然后它将这些转换为 React 中的 <span>,每个 URL 都位于 <a href 标签内。代码运行良好,但我似乎无法为其编写 Jest 测试。

这是我目前尝试过的方法:

expect(convertHyperlinks('http://whosebug.com'))
  .toStrictEqual(<span><a href='http://whosebug.com' target='_blank'>whosebug.com</a></span>);

并且:

expect(convertHyperlinks('http://whosebug.com'))
  .toMatchInlineSnapshot(<span><a href='http://whosebug.com' target='_blank'>whosebug.com</a></span>);

在前一种情况下,我收到“序列化为同一字符串”消息。

在后一种情况下,显示的是:

Expected properties: <span><a href="http://whosebug.com" target="_blank">whosebug.com</a></span>
Received value:      <span><a href="http://whosebug.com" target="_blank">whosebug.com</a></span>

可能有人知道如何为此建立一个及格测试吗?

罗伯特

更新:这是相关函数的代码:

export const convertHyperlinks = (text: string): React.Node => {
  // Find all http instances
  const regex = /http\S*/g;
  const hyperlinkInstances = text.match(regex);

  if (!hyperlinkInstances) {
    return <span>{text}</span>;
  }

  // Break up `text` into its logical chunks of strings and hyperlinks
  let items = [];
  let idx1 = 0;
  let idx2 = -1;

  hyperlinkInstances.forEach((hyperlink) => {
    idx2 = text.indexOf(hyperlink, idx1);
    if (idx2 === idx1) {
      items.push(hyperlink);
      idx1 += hyperlink.length;
    } else {
      items.push(text.substring(idx1, idx2));
      items.push(hyperlink);
      idx1 = idx2 + hyperlink.length;
    }
  });

  if (idx1 < text.length) {
    items.push(text.substring(idx1, text.length));
  }

  return (
    <span>
      {items.map((item) => {
        if (item.includes('http://')) {
          const plainLink = item.replace('http://', '');
          return (
            <a href={item.toLowerCase()} target='_blank' key={plainLink}>
              {plainLink}
            </a>
          );
        } else {
          return item;
        }
      })}
    </span>
  );
};

您正在从方法返回一个 ReactNode,它是一个对象。但是你试图断言只是一个字符串。没用。

这就是您可能从该方法中得到的结果,

因此,您必须针对您获得的对象进行断言,而不是您现在这样做的方式,

const result = convertHyperlinks('http://whosebug.com')
expect(result.props[0].key).equals('whosebug.com');
// similar kind of assertions.

此外,我建议你走组件路线,只在测试方法中渲染组件并断言元素的存在,而不是深入研究反应对象。

同样的表示如下,

这是您的组件,

const ConvertToHyperlinks = ({text}: {text: string}) => {
  // your logic and then returning DOM elements.
  return <></>;
}

然后你可以在任何地方使用它,

<div>
  <ConvertToHyperlinks text={'https://www.test.com/'} />
</div>

然后在你的单元测试中,

const renderedComponent = render(<ConvertToHyperlinks text={''https://www.anytyhing.com}/>);
expect(renderdComponent.getByText('anytyhing.com')).ToBeInTheDocument();

这里我使用了一些Rect Testing Library方法,但是即使你使用酶等,想法也是一样的