Nadia Hansen
Nadia Hansen

Reputation: 937

Pester test if list is empty do not run the tests

I would like to be able to skip tests if list is empty.

a very simplified example:

No name is -eq to "jens", therefore the $newlist would be empty, and of course the test will fail, but how do i prevent it from going though this test if the list is empty?

context {
    BeforeAll{
    $List = @(Harry, Hanne, Hans)
    $newlist = @()
    
    foreach ($name in $List) {
        if (($name -eq "Jens")) {
            $name += $newlist
    }
    }
    }
    It "The maximum name length is 10 characters" {
        $newlist |ForEach-Object {$_.length | Should -BeIn (1..10) -Because "The maximum name length is 10 characters"}
    }
}

fail message:

Expected collection @(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) to contain 0, because The maximum name length is 10 characters, but it was not found.

Upvotes: 1

Views: 474

Answers (2)

JohnLBevan
JohnLBevan

Reputation: 24400

Pester provides a -Skip switch parameter: https://pester.dev/docs/usage/skip

You can toggle this switch by using a colon after the parameter, then providing a bool (or a condition which evaluates to bool); e.g.

It "The maximum name length is 10 characters" -Skip:(-not $newlist) {
    $newlist |
      ForEach-Object {
          $_.length | 
            Should -BeIn (1..10) -Because "The maximum name length is 10 characters"
      }
}

Upvotes: 0

Mark Wragg
Mark Wragg

Reputation: 23355

You can achieve this by using Set-ItResult, which is a Pester cmdlet that allows you to force a specific result. For example:

Describe 'tests' {
    context 'list with content' {

        BeforeAll {
            $List = @('Harry', 'Hanne', 'Hans')
            $newlist = @()
    
            foreach ($name in $List) {
                if (($name -eq "Jens")) {
                    $newlist += $name
                }
            }
        }
        
        It "The maximum name length is 10 characters" {
            if (-not $newlist) {
                Set-ItResult -Skipped
            }
            else {
                $newlist | ForEach-Object { $_.length | Should -BeIn (1..10) -Because "The maximum name length is 10 characters" }
            }
        }
    }
}

Note that there was an error in your example ($newlist wasn't being updated with name, you were doing the reverse) which I've corrected above, but your test doesn't actually fail for me in this example (before adding the Set-ItResult logic). I think this is because by using ForEach-Object with an empty array as an input the Should never gets executed when its empty, so with this approach your test would just pass because it never evaluates anything.

Upvotes: 2

Related Questions