代码之家  ›  专栏  ›  技术社区  ›  aaayumi

如何为单元测试获取嵌套props函数的值

  •  1
  • aaayumi  · 技术社区  · 6 年前

    this.props.user.getPerson().getData()

    getPerson

    getData 返回与人员相关的数据。

    它的可读性是分开的,我想让它用于单元测试。

    测试1:

     let _wrapper,
        initialProps
    
      beforeEach(() => {
        initialProps = {
          user: {
            getPerson: () => {}
          }
        }
        _wrapper = shallow(<Test1 {...initialProps} />)
      })
    some tests...
    })
    

    TypeError: Cannot read property 'getData' of undefined .

    测试2

     let _wrapper,
        initialProps
    
      beforeEach(() => {
        initialProps = {
          user: {
            getPerson: () => { getData: () => {} }
          }
        }
        _wrapper = shallow(<Test2 {...initialProps} />)
      })
    some tests...
    })
    

    与Test1相同的错误。

    如何获取嵌套道具函数的值?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Brian Adams    6 年前

    你需要 wrap object literals in parentheses to return them from arrow functions :

    initialProps = {
      user: {
        getPerson: () => ({ getData: () => { } })  // wrap in parentheses
      }
    }