Question:
What would be the best way to import functions to tests that don't reside in the same directory?
Example
π src
π Get-Emoji.ps1
π test
π Get-Emoji.Tests.ps1
Inb4
- Pester documentation[1] suggests test files are placed in the same directory as the code that they test. No examples of alternatives provided.
- Pester documentation[2] suggests dot-sourcing to import files. Only with examples from within same directory
- Whether breaking out tests from the src is good practice, is to be discussed elsewhere
- Using Powershell Core for cross platform support on different os filesystems (forward- vs backward slash)
[1] File placement and naming convention
[2] Importing the tested functionsPester considers all files named .Tests.ps1 to be test files. This is the default naming convention that is used by almost all projects.
Test files are placed in the same directory as the code that they test. Each file is called as the function it tests. This means that for a function Get-Emoji we would have Get-Emoji.Tests.ps1 and Get-Emoji.ps1 in the same directory. What would be the best way to referencing tests to functions in Pester.
Pester tests are placed in .Tests.ps1 file, for example Get-Emoji.Tests.ps1. The code is placed in Get-Emoji.ps1.
To make the tested code available to the test we need to import the code file. This is done by dot-sourcing the file into the current scope like this:
Example 1
# at the top of Get-Emoji.Tests.ps1 BeforeAll { . $PSScriptRoot/Get-Emoji.ps1 }
Example 2
# at the top of Get-Emoji.Tests.ps1 BeforeAll { . $PSCommandPath.Replace('.Tests.ps1','.ps1') }
. ([IO.Path]::Combine($PSEditor.Workspace.Path, "path/to/function/Get-Emoji.ps1"))
β Wellbeloved