首页 > 解决方案 > 使用 react-testing 库测试到达路由器

问题描述

通过到达路由器 https://testing-library.com/docs/example-reach-router使用反应测试库

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

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

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

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

标签: javascriptreactjsjestjsreact-testing-libraryreach-router

解决方案


这种语法称为解构赋值,设置函数参数的默认值

看看这个例子:

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: / ƒ (){}

推荐阅读