0

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 Answer 1

2

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: / ƒ (){}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.