Behind the PowerShell Pipeline logo

Behind the PowerShell Pipeline

Subscribe
Archives
July 16, 2024

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
Personally, if I'm writing a Pester test for a module, I wrap all of my tests in an `InModuleScope` block. This way, I can be sure that I'm testing the module as it will be used in the real world.
InModuleScope MyFunction {

    Describe CommandFoo {

    }

    Describe CommandBar {

    }

}
Let's look at an example using my `Get-OSDetail` function that I'll put into a module.
Get a premium subscription for full article and archive access

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.

Want to read the full issue?
GitHub Bluesky LinkedIn About Jeff
Powered by Buttondown, the easiest way to start and grow your newsletter.