How to mock script invocation with Pester?

Viewed 33

I want to create a mock with Pester which is supposed to be called in stead of a script. Simplified example below.

somecmd.ps1

# This is the script I want to not be called in my test.

Write-Host "Output from somecmd.ps1"
throw "Error, should have been mocked"

somemodule.psm1

# This is the module I am testing.

function ModuleFunction{
    .\somecmd
}

function somecmd {
    Write-Host "Output from somecmd in somemodule"
    throw "Error, should never be called"
}

somemodule.Tests.ps1

# This is my Pester test.

BeforeAll {
    Import-Module .\somemodule.psm1 -Force
}

Describe 'SomeTest' {
    It 'Should mock' {
        # How must I declare the mock below so that somecmd.ps1 is not invoked?
        Mock somecmd { Write-Host "Output from mock" } -ModuleName somemodule
        ModuleFunction
    }
}

As stated in the comment above, my problem is I cannot figure out how to declare the mock, so that the test will use that in stead of actually invoking somecmd.ps1.

I tried looking into this issue, but following the suggestion there did not solve my problem.

Unfortunately, in my real scenario, it is not an option for me to re-write the module to better support testing.

I am running:

  • PowerShell: 5.1.19041.1682
  • Pester: 5.3.3

Does anyone have an idea?

1 Answers

From the GitHub Issue you linked, I don't think you can mock a *.ps1 script directly.

However, a simple workaround is to wrap your call to .\somecmd.ps1 in a separate function, and then mock that...

somemodule.psm1

function Invoke-SomeCmd
{
    .\somecmd
}

function ModuleFunction{
    # do some stuff
    Invoke-SomeCmd
    # do some more stuff
}

somemodule.Tests.ps1

BeforeAll {
    Import-Module .\somemodule.psm1 -Force
}

Describe 'SomeTest' {
    It 'Should mock' {
        Mock "Invoke-SomeCmd" {
            Write-Host "Output from mock"
        } -ModuleName somemodule
        ModuleFunction
    }
}

and then you get this output:

Starting discovery in 1 files.
Discovery found 1 tests in 327ms.
Running tests.
Output from mock
[+] C:\src\so\pester\somemodule.tests.ps1 992ms (274ms|433ms)
Tests completed in 1.02s
Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0
Related