Search code examples
powershellpester

Writing pester test for existing script


I've started reading up on the Pester framework and I could use some thinking power on how to handle my situation. We have several existing PowerShell scripts.

Simple example MyScript.ps1 (pseudo code):

  Import Module

  Dot source a couple of other PowerShell scripts

  Declare some variables

  Get-ChildItem and delete files older then x days

If I were to load this file into my test file MyScript.Test.ps1 the code would execute which I do not want. Should I re-factor the main file so everything is wrapped in a function.. Should I not import the main file at all and write tests for the functionality used inside the main script file.. Mind you, there are dozens of different PowerShell scripts which I have to write tests for and they all have combinations of either code OR code + functions.

I would like to know how you would handle this?


Solution

  • Per this answer: Pester how to test powershell script which does not have functions? the easiest way to test a script that isn't a function is to create an alias for it:

    BeforeAll {
        Set-Alias -Name MyScript -Value MyScript.ps1
    }
    

    You can then call this alias within your It blocks when testing the script. I would say however that you should look to write individual test scripts for all of your individual function files, this is generally good practice and would allow these individual tests to be run when modifying those functions as an initial check.

    Note that also your script will still be run when you invoke the Alias, so if you want to ensure it doesn't do anything destructive, or if you need to simulate input for it, you need to use Mocking: https://pester.dev/docs/usage/mocking.

    Having individual test files for your various functions could then mean you can Mock those functions away when testing the parent script.