【问题标题】:How to match a React node in @testing-library/react?如何匹配@testing-library/react 中的 React 节点?
【发布时间】:2021-08-17 08:46:38
【问题描述】:

我想测试 prop 是否正确地丰富了节点值,然后传递给组件。问题是,即使test和component有相同的node,jest也会识别为不同的。

基本上,我的组件呈现以下内容:

function MyComponent({columns}){
   let columnsWithDescriptions = columns.map(c => ({
      ...c,
      description: <div>{c.name} - {c.last_name}</div>
   });

   return <Table columns={columnsWithDescriptions} />
}

我执行的测试:

test('check props', function(){
   render(<MyComponent columns={[{name: 'abc', last_name: 'def'}]} />
   expect(Table).toHaveBeenCalledWith({
     columns: [{name: 'abc', last_name: 'def', description: <div>abc - def</div>}],
   }); 
});

它几乎可以工作,但由于节点内部包含不同的字符串而失败:

                "description": <div>
        -         abc | def
        +         abc
        +          | 
        +         def
                </div>,

你对如何解决这个问题有什么建议吗?

【问题讨论】:

    标签: reactjs jestjs react-testing-library


    【解决方案1】:

    经过一番调查,我找到了解决方案。 两个元素相等的假设是错误的。在代码中:

    const name = 'abc';
    const last = 'edf';
    <div> {name} - {last} </div> !== <div> abc - edf </div>
    

    第一个节点有 3 个子节点,第二个节点只有一个子节点。

    我在测试比较中修复了它:

    <div> {name} - {last} </div> === <div> {'abc'} - {'edf'} </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-02
      • 2019-08-29
      • 2021-02-28
      • 1970-01-01
      • 2019-08-31
      • 2019-08-18
      • 2020-02-27
      • 2019-05-21
      相关资源
      最近更新 更多