Skip to content

Commit 363030f

Browse files
fix: use top-level BeforeAll to recompute variables for Run phase
Pester v5 Discovery and Run are separate executions. Script-level variables set during Discovery do not exist during Run, so referencing them via $script: in a Describe BeforeAll yields null. Replace the Describe-level BeforeAll bridge with a top-level BeforeAll that recomputes all variables from $Path, which Pester re-passes via container data to both phases.
1 parent bba415d commit 363030f

File tree

1 file changed

+24
-9
lines changed

1 file changed

+24
-9
lines changed

src/tests/Module/PSModule/PSModule.Tests.ps1

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,32 @@ Write-Host "Has class exporter: $hasClassExporter"
4040
Write-Host "Expected classes: $($expectedClassNames -join ', ')"
4141
Write-Host "Expected enums: $($expectedEnumNames -join ', ')"
4242

43-
Describe 'PSModule - Module tests' {
44-
BeforeAll {
45-
# Re-expose discovery-phase variables for the Run phase (It blocks).
46-
# Pester v5 script-scope variables are visible during Discovery but not inside It blocks.
47-
$moduleName = $script:moduleName
48-
$moduleManifestPath = $script:moduleManifestPath
49-
$hasClassExporter = $script:hasClassExporter
50-
$expectedClassNames = $script:expectedClassNames
51-
$expectedEnumNames = $script:expectedEnumNames
43+
# Run-phase setup — recompute from $Path (available in both Discovery and Run phases).
44+
# Script-level variables above only exist during Discovery; BeforeAll runs only during Run.
45+
BeforeAll {
46+
$moduleName = Split-Path -Path (Split-Path -Path $Path -Parent) -Leaf
47+
$moduleManifestPath = Join-Path -Path $Path -ChildPath "$moduleName.psd1"
48+
$moduleRootPath = Join-Path -Path $Path -ChildPath "$moduleName.psm1"
49+
50+
$moduleContent = if (Test-Path -Path $moduleRootPath) { Get-Content -Path $moduleRootPath -Raw } else { '' }
51+
$hasClassExporter = $moduleContent -match '#region\s+Class exporter'
52+
53+
$expectedClassNames = @()
54+
$expectedEnumNames = @()
55+
if ($hasClassExporter) {
56+
if ($moduleContent -match '\$ExportableClasses\s*=\s*@\(([\s\S]*?)\)') {
57+
$expectedClassNames = @([regex]::Matches($Matches[1], '\[([^\]]+)\]') | ForEach-Object { $_.Groups[1].Value })
58+
}
59+
if ($moduleContent -match '\$ExportableEnums\s*=\s*@\(([\s\S]*?)\)') {
60+
$expectedEnumNames = @([regex]::Matches($Matches[1], '\[([^\]]+)\]') | ForEach-Object { $_.Groups[1].Value })
61+
}
5262
}
63+
Write-Host "Run phase - Module: $moduleName"
64+
Write-Host "Run phase - Manifest: $moduleManifestPath"
65+
Write-Host "Run phase - Has class exporter: $hasClassExporter"
66+
}
5367

68+
Describe 'PSModule - Module tests' {
5469
Context 'Module' {
5570
It 'The module should be importable' {
5671
{ Import-Module -Name $moduleManifestPath -Force } | Should -Not -Throw

0 commit comments

Comments
 (0)