我如何在单元测试中模拟可用的道具= TRUE,以便可以隔离测试我的react组件

时间:2019-08-31 04:51:53

标签: reactjs unit-testing react-testing-library

我正在尝试对生成子组件列表的组件进行单元测试,并且在我的代码中避免在空对象上运行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()


    })
})

这是测试失败时显示的内容:

  

找不到带有文本的元素:乔纳森·史密斯(Jonathan Smith)。这可能是因为文本被多个元素分解了。在这种情况下,您可以为文本匹配器提供一个功能,以使匹配器更加灵活。

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

1 个答案:

答案 0 :(得分:2)

当您以以下方式传递道具时:

<OratorList {...props} />

一个数组只是散布在道具中,相反,您要做的是:

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

其中oratorsOratorList中收到的道具的名称