Description
General summary of the issue
Pester is placing mock inside of module scope even when -ModuleName
isn't specified. Diagnostic output incorrectly assets that ModuleName was specified.
Describe your environment
Pester version : 5.2.2 /User/powershell/Modules/Pester/5.2.2/Pester.psm1
PowerShell version : 7.1.3
OS version : Unix 11.0.0
Step to reproduce
ExampleModule.psm1 - the function I am attempting to mock
function Invoke-MyExampleFunction {
[Cmdletbinding()]
param()
Write-Error "Mock failed. Original function was called."
}
MockInjection.psm1 - I call the function in this module to insert the mock into my test file. This allows me to easily reuse my common mocks
function Invoke-MockInjection {
Mock Invoke-MyExampleFunction {
Write-Host 'Mocked from MockInjection module'
}
}
MyScript.ps1
Import-Module ExampleModule
Invoke-MyExampleFunction
MyScript.Tests.ps1
$PesterPreference = New-PesterConfiguration @{
Output = @{
Verbosity = 'Diagnostic'
}
}
Describe "Example Tests" {
BeforeAll {
Import-Module ExampleModule
Import-Module MockInjection
# The mock works as expected if defined inside of the BeforeAll block in the test script
# Mock Invoke-MyExampleFunction {
# Write-Host "Mocked from inside BeforeAll block. Works as expected."
# }
# This does not work. See below diagnostic output.
Invoke-MockInjection
$scriptPath = $PSCommandPath -replace '.Tests.ps1', '.ps1'
}
It "Mocks correctly" {
{ . $scriptPath } | Should -Not -Throw
}
}
The mock works as expected when it is created inside of the test script itself. If it is injected from another module for the purposes of reusing some mock behavior, it fails. Diagnostic output makes it appear as though moduleName is being specified when it is not.
diagnostic output. Note line 4 and 5 that ModuleName was specified when it was not.
Mock: Setting up default mock for MockInjection - Invoke-MyExampleFunction.
Mock: We are in a block, one time setup or similar. Returning mock table from test block.
Mock: Resolving command Invoke-MyExampleFunction.
Mock: ModuleName was specified searching for the command in module MockInjection.
Mock: We are already running in MockInjection. Using that.
Mock: Found the command Invoke-MyExampleFunction in a different module.
Mock: Mock does not have a hook yet, creating a new one.
Mock: Defined new hook with bootstrap function PesterMock_MockInjection_Invoke-MyExampleFunction_8683fddf-5380-43a6-a489-ab324f65a01b and aliases Invoke-MyExampleFunction, ExampleModule\Invoke-MyExampleFunction.
Mock: Adding a new default behavior to MockInjection - Invoke-MyExampleFunction.