检查子组件是否已渲染-笑话,酶

时间:2018-06-21 20:49:33

标签: javascript reactjs jestjs enzyme

在单元测试中,我想测试父组件是否成功呈现其子组件。这是代码:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.find(Child).length).toEqual(1);
  });
});

父母:

const Parent = observer(({ store }) => {
  const bookList = toJS(store.planets);
  return (
    <div>
      <div className={style.planet_container}>
        {bookList.map(book => {
          return <Child key={book.name} name={book.name} />;
        })}
      </div>
    </div>
  );
});

以上代码取自here,但无效。我收到以下错误:

  

预期1,收到0'

我要去哪里错了?我在Jest 23.1.0中使用酶3.3。

5 个答案:

答案 0 :(得分:6)

您可以使用containsMatchingElement()检查父组件是否已渲染其子组件。

基于酶docs

返回patternNode react元素是否与渲染树中的任何元素匹配。

您的测试应如下所示:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent store={store} />);
    expect(wrapper.containsMatchingElement(<Child />)).toEqual(true);
  });
});

答案 1 :(得分:3)

Enzyme允许按组件的displayName查找:

来自酶API文档:

const StyledDiv = styled.div<{ active?: boolean }>`
    ${({ active }) =>
        active &&
        'background-color:grey'};
`;

           OR
 const StyledDiv = styled.div<{ active?: boolean }>`
     background-color: ${(props: any) => props.grey};
`;

因此,为了测试是否已渲染Child组件,您可以简单地通过其 displayName 对其进行引用。

您可以print the wrapper's HTML stringconst wrapper = shallow(<MyComponent />); expect(wrapper.find('Foo')).to.have.lengthOf(1);


如果您的组件是dynamic,则可以将其displayName设置为固定的,这样测试将更加安全:

console.log( wrapper.debug() )

答案 2 :(得分:2)

尝试一下:

describe('Parent Component', () => {
  it('renders Child component', () => {
    const wrapper = shallow(<Parent />);
    expect(wrapper.find(Child)).toHaveLength(1);
  });
});

答案 3 :(得分:0)

孩子没有渲染,因为您没有正确嘲弄道具(在本例中为道具“存储”)。

尝试一下:

it('renders Child component', () => {
  const wrapper = shallow( < Parent / > );
  wrapper.setProps({
    store: {
      planets: [{
          name: "name 1"
        }
      ]
    }
  });
  expect(wrapper.find(Child)).toHaveLength(1);
});

答案 4 :(得分:0)

如果要检查子组件元素

 let wrapper1 = mount(<PersonalInfo {...personalInfodata} />);
    expect(wrapper1.find('ChildComponent').children(0).find('.description').text().length).toBeGreaterThan(0);

您可以做这样的事情

相关问题