【问题标题】:Testing reach router with react-testing library使用 react-testing 库测试到达路由器
【发布时间】:2019-12-12 02:51:59
【问题描述】:

通过reach-router 使用react 测试库 https://testing-library.com/docs/example-reach-router

function renderWithRouter(
  ui,
  { route = '/', history = createHistory(createMemorySource(route)) } = {}
) 

函数的第二个参数,怀疑是一个对象,{}。但是使用 '=' 而不是 ':' 意味着它不是名称-值对。那是什么?

另外,两个对象之间的赋值运算符的作用是什么

{ route = '/', history = createHistory(createMemorySource(route)) } = {}

【问题讨论】:

    标签: javascript reactjs jestjs react-testing-library reach-router


    【解决方案1】:

    此语法称为Destructuring assignment,并设置函数参数的默认值

    看看这个例子:

    function drawChart({size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}) {
      console.log(size, coords, radius);
      // do some chart drawing
    }
    
    drawChart({
      coords: {x: 18, y: 30},
      radius: 30
    });
    

    在上面drawChart 的函数签名中,解构的左侧被分配给右侧的空对象字面量:{size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}。您也可以在没有右侧赋值的情况下编写函数。但是,如果您省略右侧的赋值,则该函数将在调用时寻找至少一个要提供的参数,而在其当前形式中,您可以简单地调用 drawChart() 而不提供任何参数。如果您希望能够在不提供任何参数的情况下调用函数,则当前设计很有用,当您希望确保将对象传递给函数时,另一种设计很有用。

    回到renderWithRouter函数示例

    function renderWithRouter(ui, { route = "/", history = function(){} } = {}) {
      console.log(route, history);
    }
    
    console.log(renderWithRouter({})) //output: / ƒ (){}
    

    【讨论】:

      猜你喜欢
      • 2020-08-28
      • 2021-04-01
      • 2021-01-09
      • 2020-10-22
      • 2021-09-24
      • 2019-09-02
      • 1970-01-01
      • 2019-05-21
      • 2021-06-14
      相关资源
      最近更新 更多