使用反应测试库测试到达路由器

时间:2019-12-12 02:51:59

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

将React测试库与到达路由器一起使用 https://testing-library.com/docs/example-reach-router

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

该函数的第二个参数怀疑是对象{}。但是使用'='代替':'表示其不是名称/值对。那是什么?

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

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

1 个答案:

答案 0 :(得分:2)

这种称为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: / ƒ (){}