Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 996
DarkLite1 Avatar asked Jul 16 '18 11:07

DarkLite1


People also ask

What is mocking 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.

How do you write a pester test?

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.


1 Answers

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
}
like image 109
Mark Wragg Avatar answered Oct 05 '22 02:10

Mark Wragg