Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a Pester mocked function

How is it possible to unmock a previously mocked function? Sometimes I find myself in a situation that I want to test a function that I previously mocked.

A simplified example:

Describe 'Pester mocking' {
    $testFile = Join-Path  $env:TEMP 'test.txt'

    It 'should be green' {
        Mock Out-File

        'Text' | Out-File -FilePath $testFile

        Assert-MockCalled Out-File -Times 1 -Exactly
    }
    It 'should be green' {
        # Unmock Out-File

        'Text' | Out-File -FilePath $testFile

        $testFile | Should -Exist
    }
}
like image 484
DarkLite1 Avatar asked Sep 24 '26 07:09

DarkLite1


1 Answers

Figured it out, it appears that Pester creates an alias for each mocked function. The solution would be to remove the alias from the scope. This way the real CmdLet will be called.

There are two ways of doing this depending on your version of PowerShell:

Remove-Item Alias:\Out-File
Remove-Alias Out-File

Solution:

Describe 'Pester mocking' {
    $testFile = Join-Path  $env:TEMP 'test.txt'

    It 'should be green' {
        Mock Out-File

        'Text' | Out-File -FilePath $testFile

        Assert-MockCalled Out-File -Times 1 -Exactly
    }
    It 'should be green' {
        Remove-Item Alias:\Out-File

        'Text' | Out-File -FilePath $testFile

        $testFile | Should -Exist
    }
}
like image 147
DarkLite1 Avatar answered Sep 26 '26 00:09

DarkLite1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!