Reputation: 729
I would like to test this code with Pester, but without creating a .psm1
and without creating an extra .ps1
.
# file GetSomething.ps1
function Get-Something # this is testable with pester
{
'something'
}
# Some-Other-Function or call that takes very long or can't be run in Pester.
Do-Something-Expensive-NotTestable
Get-Something
The corresponding test according to Pester Docs:
#file GetSomething.Tests.ps1
BeforeAll {
. $PSScriptRoot\GetSomething.ps1
}
Describe 'Get-Something' {
It 'Gets something' {
Get-Something | Should -Be 'something'
}
}
I found various articles online describing my issue in detail. For example https://jakubjares.com/2015/01/10/test-script-end-to-end/ is a very detailed explanation why you want to dot-source and why it is an issue with Pester. It lists possible solutions with pros and cons, but it is from 2015.
The best solution I could find was this post. The new BeforeAll
looks like this:
BeforeAll {
function Get-Functions($filePath)
{
$script = Get-Command $filePath
return $script.ScriptBlock.AST.FindAll({ $args[0] -is [Management.Automation.Language.FunctionDefinitionAst] }, $false)
}
Get-Functions GetSomething.ps1 | Invoke-Expression
}
I would imagine that almost everyone using Pester has this issue. Is there any newer/better approach to fix this with Pester v5? I do prefer .psm1
modules mostly, but sometimes I prefer script and functions in a single file and still want to test the functions in an extra file.
Upvotes: 0
Views: 38