问题
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 calldrawChart()
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