我如何在我的单元测试中模仿 props available = TRUE 以便我可以单独测试我的反应组件

How do I mimic props available = TRUE in my unit test so I can test my react component in isolation

我正在尝试对生成子组件列表的组件进行单元测试,并在我的代码中避免在空对象上 运行ning array.map,我有一个条件检查确保道具可用。当我在浏览器中渲染组件时它可以工作,但是当我尝试 运行 单元测试时,即使使用 async/await,它也总是转到 props = false 分支。

我已将道具硬编码到测试中,但它仍然不起作用。我如何模仿 props=true 以便我可以测试呈现列表的组件?

我试过使用async/await,所以有一个暂停让道具可用。不知何故,我认为这里发生了其他事情,但我无法弄清楚。

这是我的组件:


const OratorList = ({ orators }) => {
    return (
        <div className="orator-list section">
            {orators ? orators.map(orator => {
                return (
                    <Link className="orator-item" to={ROUTES.ORATOR+'/'+orator.id} key={orator.id} >
                        <OratorSummary orator={orator} key={orator.id} />
                    </Link>
                )

            }): null}

        </div>
    );
};

export default OratorList;

这是测试:


describe('Orator List', () => {
    test('it renders a list of orator cards with their first name, last name, age, and parent of the orator', () => {

        //Arrange
        const orator1 = {
            orator: {
                id: 1,
                firstName: 'Jonathan',
                lastName: 'Smith',
                dateOfBirth: '2005-09-24',
                parentName: 'Denise Smith'
            }
        }
        const orator2 = {
            orator: {
                id: 2,
                firstName: 'Amy',
                lastName: 'Smith',
                dateOfBirth: '2007-01-15',
                parentName: 'Denise Smith'
            }
        }
        const orator3 = {
            orator: {
                id: 3,
                firstName: 'Susan',
                lastName: 'Smith',
                dateOfBirth: '2011-06-06',
                parentName: 'Denise Smith'
            }
        }

        const props = [orator1, orator2, orator3]

        //Act
        const {getByText} = render(<OratorList {...props} />)


        //Assert

        const nameNode = getByText(`${orator1.orator.firstName} ${orator1.orator.lastName}`)
        const parentNode = getByText(`${orator1.orator.parentName}'s Family`)

        expect(nameNode).toBeDefined()
        expect(parentNode).toBeDefined()


    })
})

这是测试失败时打印出来的内容:

Unable to find an element with the text: Jonathan Smith. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

<body>
  <div>
    <div
      class="orator-list section"
    />
  </div>
</body>

当你传入道具时:

<OratorList {...props} />

一个数组只是被散布到 props 中,而你需要做的是:

const props = [orator1, orator2, orator3];
const {getByText} = render(<OratorList orators={props} />)

其中 orators 是在 OratorList

中收到的道具的名称