We're trying to assess if Invoke-Command
has been called exactly one time.
Script.ps1
$job = Invoke-Command -ScriptBlock {'test'} -ComputerName localhost -AsJob
$job | Wait-Job
Script.Tests.ps1
BeforeAll {
$testScript = $PSCommandPath.Replace('.Tests.ps1', '.ps1')
Mock Invoke-Command
}
Describe 'Test' {
It 'should be green' {
. $testScript
Should -Invoke Invoke-Command -Times 1 -Exactly -Scope It
}
}
The problem is mocking the job object in Pester. When the job is not mocked, Wait-Job
will throw an error that it didn't receive a job object.
How is it possible to mock a PowerShell job object in Pester
?
Pester provides a set of Mocking functions making it easy to fake dependencies and also to verify behavior. Using these mocking functions can allow you to "shim" a data layer or mock other complex functions that already have their own tests.
Writing A Passing Pester TestOpen up the C:\Pester101\Install-Pester. ps1 file in your favorite editor and insert a single line Write-Output "Working!" as shown below. function Install-Pester { param() Write-Output "Working!" } Save the file and now open the C:\Pester101\Install-Pester.
One solution might be to have the Mock
of Invoke-Command still create a legitimate job, but executing some script/code that you deem safe for the purpose of testing.
To do this, you need to first put the Invoke-Command
cmdlet in a variable so that you can use it via that variable (because a Mock
can't directly call its own command).
For example:
$InvokeCommand = Get-Command Invoke-Command
Mock Invoke-Command {
& $InvokeCommand -ScriptBlock {'some safe alternative code'} -ComputerName localhost -AsJob
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With