如何测试容器以告诉我它知道容纳多少物品

时间:2019-02-20 21:57:31

标签: reactjs jestjs enzyme

此组件将生成一个5 li的无序列表。我只想编写一个测试,说这个容器知道里面有多少li。我实际上使用的是Enzyme docs BUT上列出的相同代码,而不是获得所需的输出,而是得到一个空对象{}。我究竟做错了什么?注意:我还安装了Jest,所以...这似乎也使我感到困惑。 (我希望“预期”和“已接收”会返回5)

测试输出

    expect(received).toEqual(expected)

    Expected: 5
    Received: {}

组件代码

import React from "react"
import TabLink from "./TabLink";
import ErrorBoundary from "./ErrorBoundary";
import Nav from "./Nav";

export default function TabLinkContainer({selectedId, items, handleClick}) {

    const tabLinks = items.map(({id, label, isDisabled}) => (
        <ErrorBoundary key={id}>
            {/*{console.log("inside TabLinkContainer: ", selectedId, ",", id)}*/}
            <TabLink
                id={id}
                handleClick={handleClick}
                isDisabled={isDisabled}
                isSelected={selectedId === id}
                text={ typeof label === 'object' ? label.text : label}
                icon={label.icon || null}
            />
        </ErrorBoundary>
    ));
    return <Nav tabs className="scroll">{tabLinks}</Nav>;
}

测试文件

import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import TabLinkContainer from '../Tabs/TabLinkContainer';
import TabData from '../Tabs/TabsData';
Enzyme.configure({adapter: new Adapter()});

let activeTab = '0';
let post = TabData;

describe('TabLinkContainer', () => {
    const handleClick = (tab,event) => {
        event.preventDefault();
        if (active !== tab) {
            this.setState({ active: tab })
        }
    };

    it('knows number of tabs it contains', () => {
        const wrapper = mount(
           <TabLinkContainer
               selectedId={active}
               handleClick={handleClick}
               items={post}
           />
           );
        expect(wrapper.find('ul').children()).toEqual(5);
    });
});

1 个答案:

答案 0 :(得分:0)

您正在尝试将ul元素的子项与数字进行比较。

您要寻找的是孩子的 count

expect(wrapper.find('ul').children().length).toEqual(5);

或使用expect方法内置的toHaveLength

expect(wrapper.find('ul').children()).toHaveLength(5);