Testing reach router with react-testing library

天大地大妈咪最大 提交于 2021-02-11 17:41:42

问题


Going through using react testing library with reach-router https://testing-library.com/docs/example-reach-router

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

Second argument to the function , suspect is an object, {} . But '=' is used instead of ':' means its not a name-value pair. So what is it?

Also, what is the purpose of the assignment operator between two objects

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

回答1:


This syntax called Destructuring assignment with setting a function parameter's default value

Take look at this example:

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
});

In the function signature for drawChart above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: {size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}. You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply call drawChart() without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

Back to the renderWithRouter function example

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

console.log(renderWithRouter({})) //output: / ƒ (){}


来源:https://stackoverflow.com/questions/59297023/testing-reach-router-with-react-testing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!