javascript 检查子组件是否呈现 - Jest、Enzyme

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50977230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:21:45  来源:igfitidea点击:

Check if child component rendered - Jest, Enzyme

javascriptreactjsjestjsenzyme

提问by maverick

In my unit test, I want to test whether the parent component is successfully rendering its child component. Here is the code:

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

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

Parent:

家长:

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>
  );
});

Above code is taken from here, but it's not working. I am getting the following error:

以上代码取自here,但不起作用。我收到以下错误:

Expected 1, Received 0'

预期 1,收到 0'

Where am I going wrong? I am using Enzyme 3.3 with Jest 23.1.0.

我哪里错了?我在 Jest 23.1.0 中使用 Enzyme 3.3。

回答by Felipe Suárez

Child is not rendering because you are not mocking the props (in this case the prop "store") correctly.

Child 没有渲染,因为您没有正确地模拟道具(在这种情况下是道具“商店”)。

Try this:

试试这个:

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

回答by Ekown

You can check whether a parent component has rendered its child component using containsMatchingElement().

您可以使用containsMatchingElement().

Based on Enzyme docs:

基于酶文档

Returns whether or not a patternNode react element matches any element in the render tree.

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

Your test should look like this:

您的测试应如下所示:

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

回答by Amarnathrao Sulake

Try this:

试试这个:

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