0

some-table.jsx这是我正在测试的功能组件:

import React from 'react';

const SomeTable = ({ somethings }) => (
  <>
    {somethings.map(something => {
      return <SomeRow key={something} something={something} />
    })}
  </>
);

export const SomeRow = ({ something }) => {
  return <p>{something}</p>
}

export default SomeTable;

这是我的测试文件:

import { create } from "react-test-renderer";
import SomeTable, { SomeRow } from "../common/ui/some-table";

test("check SomeTable has row", () => {
  const renderer = create(<SomeTable somethings={["Hello", "World"]} />);
  const allRows = renderer.root.findAllByType(SomeRow);
  expect(allRows.length).toBe(2);
});

该测试通过。但是,如果我SomeRow进入它自己的文件,它就会失败:

some-table.jsx

import React from 'react';
import { SomeRow } from './some-row';

const SomeTable = ({ somethings }) => (
  <>
    {somethings.map(something => {
      return <SomeRow key={something} something={something} />
    })}
  </>
);

export default SomeTable;

some-row.jsx

import React from 'react';

export const SomeRow = ({ something }) => {
  return <p>{something}</p>
}

失败:

expect(received).toBe(expected) // Object.is equality

Expected: 2
Received: 0

任何想法为什么会这样?感谢您的阅读。

4

1 回答 1

1

在创建这些...测试文件来解决的实际场景中Some,问题是由 React 的memo()函数引起的:

import React, { memo } from 'react';
...
export default memo(SomeRow);

一种解决方法如下:

const allRows = renderer.root.findAllByType(SomeRow.type);

bensampaio 提供该提示的道具。您还会在该链接上找到许多其他可能对您有所帮助的讨论,包括:

Pin react, react-dom, react-test-rendererto 16.11.0,最重要的是添加对 的依赖react-is@16.11.0,或者使用如下的谓词:

const elementByType = (type) => (element) => (
    element.type === type // Match non-memo'd
    || element.type === type.type // Match memo'd
);

还应该指出的是,我也做了一些愚蠢的事情。进口是错误的。这个:

import SomeTable, { SomeRow } from "../common/ui/some-table";

应该是这样的:

import SomeTable from "../common/ui/some-table";
import { SomeRow } from "../common/ui/some-row";
于 2021-07-20T09:58:49.187 回答