Pester Mock imported module

1.4k Views Asked by At

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?

1

There are 1 best solutions below

0
On

The -ModuleName parameter tells Mock 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 your test.psm1 module should be intercepted and replaced with the mock, but any calls from outside the module (e.g. in your test-tests.ps1) still call the original testScript.

From https://pester-docs.netlify.app/docs/usage/modules:

Notice that in this example test script, all calls to Mock and Should -Invoke have had the -ModuleName MyModule parameter added. This tells Pester to inject the mock into the module's scope, which causes any calls to those commands from inside the module to execute the mock instead.

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

function testScript
{
    write-host 'hello'
}

function testAnother
{
    testScript
}

and update your test suite to be this:

test-tests.ps1

Describe "test" {
    Context "test call" {
           Import-Module .\test.psm1
           Mock -ModuleName 'test' testScript { write-host 'hello3' } 
           testScript
           testAnother
    }
}

If you try with and without -ModuleName 'test' you'll see the output is either

hello3
hello

or

hello
hello3

depending on where the mock is being injected (i.e. inside the module, or inside the test suite).