powershellpesterpester-5

All tests with variables are failing in Pester


I have started using Pester to write test cases for my PowerShell scripts, but unfortunately, I am failing in even simple tests. For any test, if there is a variable in the It block the test fails even though it should pass.

Below is a simplified code:

Describe 'Basic Pester Tests' {
  It 'A test that should be true' {
    $true | Should -Be $true
  }
}
Describe 'should exist with variables test' {
    $someFile = 'C:\Scripts\EnableFlash.ps1'
    It "$someFile should exist" {
      $someFile | Should -Exist
    }
}

Describe 'should exist without variable test' {
  It "'C:\Scripts\EnableFlash.ps1' should exist" {
    'C:\Scripts\EnableFlash.ps1' | Should -Exist
  }
}

Describe 'compare for addition' {
  $a = 10; $b = 20
  It "test for variables" {
    $($a+$b) | Should -Be 30
  }
}

In the above code, the test should exist with variables test fails while the test should exist without variable test succeeds.

Output: Output of the script execution

I am using PowerShell 5.1 and Pester 5.1.1


Solution

  • In recent Pester versions, variables outside of the It are out of scope and cannot be referenced in your test. You should either place them in the It block or define them earlier inside a BeforeAll, etc, block.

    Some info here: Discovery and Run