Pester Testing with InModuleScope
In a recent article, we looked at writing a Pester test that required mocking private functions. These are functions intended to be used within your code, not exposed to the user. Often, we use private helper functions as wrappers to commands that we would otherwise be unable to test with Pester.
The challenge is that in a stand-alone function, exposing the private functions to Pester adds a little complexity to the test. However, if we are writing a module, we have another alternative. Pester tests can be challenging to write because of scope. Fortunately, Pester includes a feature that makes it easier to test or mock private functions in a module. I want to show you how to wrap your tests in an InModuleScope
block.
You can limit the scoping to the tests that need to access the private functions.
Describe MyCode {
InModuleScope MyFunction {
It 'should return a string' {
$result = MyFunction
$result | Should -Be 'This is a demo script file.'
}
It 'should fail on a bad computername' {
$result = MyFunction -ComputerName 'BadComputer'
$result | Should -Throw
}
} #InModuleScope
#this is NOT tested in the module scope
It 'Should accept a PSCredential' {
#TBD
} -pending
} #describe