Search code examples
powershellmockingpester

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

  • 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
    }