'How to mock a job in Pester?
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?
Solution 1:[1]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mark Wragg |
