Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

pester-cli-testing

БесплатноБез исполняемых скриптовНе проверен

Use when the code under test is a PowerShell script, function, cmdlet or CLI run from pwsh. Sets up Pester v5: Describe/Context/It blocks, Should assertions…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

pester-cli-testing

Overview

Per pester-install, Pester is the standard PowerShell test framework for unit, integration, and acceptance testing of scripts, functions, modules, and CLI tools invoked from pwsh. It supports Windows PowerShell 3.0 - 5.1 and PowerShell 6.0.4+ across Windows, Linux, and macOS. When the unit-under-test is a shell script or binary on Linux/macOS, use bats-testing instead; Pester is the correct choice whenever the subject or test is PowerShell.

Step 1 - Install

Per pester-install, Windows 10 / Server 2016+ ship with Pester 3.4.0 built-in. The bundled version cannot be updated via Update-Module alone because its publisher certificate differs from the community-signed Gallery version. Install Pester v5 side-by-side:

# Windows (5.1 or pwsh 7+): -Force enables side-by-side; -SkipPublisherCheck
# accepts the newer certificate
Install-Module -Name Pester -Force -SkipPublisherCheck

# Linux / macOS (pwsh 7+): no bundled version to conflict with
Install-Module -Name Pester

# Verify
Import-Module Pester -PassThru

Step 2 - First test file

Per pester-quick-start:

Test files must follow the *.Tests.ps1 naming convention. The outer BeforeAll block dot-sources the script under test so its functions are available to every nested block:

# Get-Greeting.Tests.ps1
BeforeAll {
    . $PSScriptRoot/Get-Greeting.ps1
}

Describe 'Get-Greeting' {
    It 'returns a greeting for the given name' {
        Get-Greeting -Name 'Alice' | Should -Be 'Hello, Alice!'
    }
}

Run with:

Invoke-Pester -Output Detailed .\Get-Greeting.Tests.ps1

Step 3 - Describe / Context / It

Per pqs, Context and Describe are nearly interchangeable. Use Describe at the top level (function or CLI command name) and Context to group scenarios:

Describe 'Invoke-Deploy' {
    Context 'when the target environment is valid' {
        It 'exits 0 and logs a success message' {
            # ...
        }
    }

    Context 'when credentials are missing' {
        It 'throws a terminating error' {
            # ...
        }
    }
}

Step 4 - Should assertions

Per pqs, Should is the assertion command. Common matchers:

$result | Should -Be 'expected'           # strict equality
$result | Should -BeExactly 'Expected'    # case-sensitive equality
$result | Should -BeLike '*partial*'      # wildcard match
$result | Should -Match 'regex\d+'        # regex match
$result | Should -BeNullOrEmpty           # null or empty string/array
$result | Should -BeGreaterThan 0
{ risky-call } | Should -Throw            # expects a terminating error
{ risky-call } | Should -Throw '*message*' # error message wildcard
$result | Should -Not -Be $null           # negated form

Step 5 - BeforeAll / BeforeEach

Per pqs, lifecycle hooks load fixtures and reset state. BeforeAll runs once per block; BeforeEach runs before every It:

Describe 'Get-Report' {
    BeforeAll {
        . $PSScriptRoot/Get-Report.ps1
        $script:TempDir = Join-Path ([System.IO.Path]::GetTempPath()) ([System.IO.Path]::GetRandomFileName())
        New-Item -ItemType Directory -Path $script:TempDir | Out-Null
    }

    AfterAll {
        Remove-Item -Recurse -Force $script:TempDir
    }

    BeforeEach {
        # reset any per-test state here
    }

    It 'writes a report file to the output directory' {
        Get-Report -OutputPath $script:TempDir
        Test-Path (Join-Path $script:TempDir 'report.csv') | Should -BeTrue
    }
}

Use $script: scope when a variable set in BeforeAll must be read inside It blocks. Variables declared with plain $var in BeforeAll are not visible inside It due to PowerShell scoping rules.

Step 6 - Mock

Per pester-mock:

"Mock mocks the behavior of an existing command with an alternate implementation."

Describe 'Send-Notification' {
    BeforeAll {
        . $PSScriptRoot/Send-Notification.ps1

        Mock Invoke-RestMethod {
            return @{ status = 'ok' }
        }

        Mock Write-Error {}    # suppress error output in test runs
    }

    It 'calls Invoke-RestMethod once with the correct URI' {
        Send-Notification -Message 'deploy done'
        Should -Invoke Invoke-RestMethod -Times 1 -Exactly
    }

    It 'passes a ParameterFilter to scope the mock to specific arguments' {
        Mock Get-Date { return [datetime]'2024-01-01' } -ParameterFilter {
            $Format -eq 'yyyy-MM-dd'
        }
        $result = Get-FormattedDate
        $result | Should -Be '2024-01-01'
    }
}

Per pm, mocks placed in BeforeAll apply to all It blocks in the enclosing Describe/Context; a mock inside an It block scopes only to that test. Use -Scope t

Полный SKILL.md на GitHub

Установить pester-cli-testing в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonreferences/ci-and-config.md

FAQ

Что делает скилл pester-cli-testing?

Use when the code under test is a PowerShell script, function, cmdlet or CLI run from pwsh. Sets up Pester v5: Describe/Context/It blocks, Should assertions, Mock, setup hooks, tags, code coverage and NUnit/JUnit XML output for CI.

Как установить скилл pester-cli-testing?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл pester-cli-testing запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить pester-cli-testing с