Unit Testing within Modules
Let's say you have code like this inside a script module (.psm1 file):
You wish to write a unit test for this module which mocks the calls to Get-Version
and Get-NextVersion
from the module's BuildIfChanged
command. In older versions of Pester, this was not possible. As of version 3.0, there are two ways you can perform unit tests of PowerShell script modules. The first is to inject mocks into a module:
For these example, we'll assume that the PSM1 file is named "MyModule.psm1", and that it is installed on your PSModulePath.
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.
When you write your test script this way, you can mock commands that are called by the module's internal functions. However, your test script is still limited to accessing the public, exported members of the module. If you wanted to write a unit test that calls Build directly, for example, it wouldn't work using the above technique. That's where the second approach to script module testing comes into play. With Pester's InModuleScope
command, you can cause entire sections of your test script to execute inside the targeted script module. This gives you access to non-exported members of the module. For example:
Notice that when using InModuleScope
, you no longer need to specify a -ModuleName
parameter when calling Mock
or Should -Invoke
for commands within that module. You are also able to directly call the Build
function, which the module does not export.
⚠️ Avoid putting in InModuleScope around your Describe and It blocks.
InModuleScope
is a simple way to expose your internal module functions to be tested, but it prevents you from properly testing your published functions, does not ensure that your functions are actually published and slows down test discovery by loading the module. Aim to avoid it altogether by using -ModuleName
on Mock
when possible or at least limit it to inside the It block like the sample above.