I'm using version pester version 5.1.0
I've created a simple test.psm1
function testScript { write-host 'hello' }
I've create a pester file let's call it test-tests.ps1
Describe "test" {
Context "test call" {
Import-Module .\test.psm1
Mock -ModuleName 'test' testScript { write-host 'hello3' }
testScript
}
}
When I run this it comes back with 'hello'. For the life of me I cannot see why Pester will not use the Mock version of testScript and return 'hello3'. Anyone see where I'm going wrong with pester?
The
-ModuleName
parameter tellsMock
where to inject the mock, not where to find the function definition.What you're currently doing is saying that any calls to
testScript
from inside yourtest.psm1
module should be intercepted and replaced with the mock, but any calls from outside the module (e.g. in yourtest-tests.ps1
) still call the originaltestScript
.From https://pester-docs.netlify.app/docs/usage/modules:
The simple fix is to remove the
-ModuleName test
parameter.To make it a bit clearer, try adding a second function into your module:
test.psm1
and update your test suite to be this:
test-tests.ps1
If you try with and without
-ModuleName 'test'
you'll see the output is eitheror
depending on where the mock is being injected (i.e. inside the module, or inside the test suite).