Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script that helps me do TDD with PowerShell and Pester in Visual Studio Code

Run Pester Unit Tests in Visual Studio Code

read more about what it is on my blog

{
"version": "0.2.0",
"configurations": [
{
"type": "PowerShell",
"request": "launch",
"name": "Test workinprogress",
"script": "workinprogress.ps1",
"args": [ "${workspaceFolder}", "${workspaceFolder}/tests", "${file}", "${lineNumber}" ]
},
{
"type": "PowerShell",
"request": "launch",
"name": "Test all",
"script": "Invoke-Pester",
"args": [ "${workspaceFolder}/tests/", "-Show Fails" ]
}
]
}
param(
[string]$workspace,
[string]$testsFolder,
[string]$fullPath,
[int]$line
)
$script:file = Split-Path $fullPath -Leaf
$script:testsRun = $false
if (Test-Path "$workspace\*.psm1") {
# if it is a module workspace, reload the module
Import-Module $workspace -Force
}
if ($script:file -like "*.Tests.ps1") {
# if it is a pester file try to get the 'current' tag
$code = [Management.Automation.Language.Parser]::ParseInput((Get-Content $fullPath -Raw), [ref]$null, [ref]$null)
$firstTag = $null
$code.FindAll([Func[Management.Automation.Language.Ast, bool]] {
param($ast)
$ast.Extent.StartLineNumber -le $line -and
$ast.Extent.EndLineNumber -ge $line -and
$ast.CommandElements -and
$ast.CommandElements[0].Value -eq "describe"
}, $true) | ForEach-Object {
$ce = $psitem.CommandElements
$tagsIndex = $ce.IndexOf(($ce | Where-Object ParameterName -in ("Tag","Tags"))) + 1
$tags = if ($tagsIndex -and $tagsIndex -lt $ce.Count) { $ce[$tagsIndex].Extent }
if ($tags) {
$firstTag = $tags.Text.Split(',')[0].Trim().Trim('"').Trim("'")
}
}
if ($firstTag) {
# if first tag has been found execute the test only for that tag
Invoke-Pester -Script $fullPath -Tag $firstTag
} else {
# if there is no tag execute the whole file
Invoke-Pester -Script $fullPath
}
$script:testsRun = $true
} else {
# not a pester file - let's try to find matching test files
if (Test-Path ($fullPath -replace ".ps1$", ".Tests.ps1")) {
# there is tests file in the same folder
Invoke-Pester -Script ($fullPath -replace ".ps1$", ".Tests.ps1")
}
if (Test-Path $testsFolder) {
(Get-ChildItem $testsFolder -Recurse -Include ($script:file -replace ".ps1$", ".Tests.ps1")) | ForEach-Object {
Invoke-Pester -Script $PSItem.FullName
}
}
$script:testsRun = $true
}
if (!$script:testsRun) {
Write-Host "There is nothing to run. Consider writing a unit test file for the $script:file file."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.