You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Describe 'function in closure' {
Context 'original' {
$closure= Outer
It 'runs normally' {
$closure| Should Not Throw
}
}
Context 'mock' {
$Inner=Get-Command-CommandType Function -Name Inner
Mock Inner { &$Inner@args }
$closure= Outer
It 'runs normally' {
$closure| Should Not Throw
}
}
}
fail with CommandNotFoundException.
The presence of .GetNewClosure() sets the difference between failure and success.
Direct calls from the console, in contrast, don't raise exceptions.
The text was updated successfully, but these errors were encountered:
When you create a new closure, it's essentially creating a script module in memory, behind the scenes, with a snapshot of whatever variables existed at the time the closure was created. The Inner function isn't actually resolved until you execute the closure, though, and at that point, this anonymous script module can't see functions defined in your script (unless that script happens to be dot-sourced into the Global scope.)
Here's how you can make it work in both cases, whether Pester is involved or not:
functionOuter {
$innerFunction=Get-Command Inner -CommandType Function
{
&$innerFunction
}.GetNewClosure()
}
This way, the Inner command resolution happens in the Outer function, not in the closure. Since you assigned the result to a variable, that variable is captured when the closure is created, and everything works fine.
Thanks: that explains a lot.
It unsettles me that the closure call would still not resolve the Inner function when they're in the same script.
Not a Pester problem, though.
See lmmarsano/pester-closure-issue for a unit test demonstrating the problem.
Something strange goes on with a closure's name bindings in unit tests.
This code
and this unit test
fail with
CommandNotFoundException
.The presence of
.GetNewClosure()
sets the difference between failure and success.Direct calls from the console, in contrast, don't raise exceptions.
The text was updated successfully, but these errors were encountered: