`Invoke-Pester` doesn't recognize `using` statements
What is the issue?
In my use case it actually concerns the using module ... statement but the general issue might be simply reproduced with any using statement as using namespace ...:
Taken the following test:
Using namespace System.Collections
Using namespace System.Collections.Generic
Describe 'Describe-Using' {
Context 'Using' {
It 'Should use the using statement' {
'Test' | Should -not -BeOfType [IList]
}
}
}
The pester test runs fine when e.g. dot-sourced (or pressing F5 in VSCode).
But when launched by Invoke-Pester from a new PowerShell session, it apparently doesn't recognize the general using statements for the individual tests, and fails the tests:
invoke-pester .\Using.Tests.ps1
Starting discovery in 1 files.
Discovery found 1 tests in 357ms.
Running tests.
[-] Describe-Using.Using.Should use the using statement 296ms (250ms|46ms)
ArgumentException: Could not find type [IList]. Make sure that the assembly that contains that type is loaded.
Tests completed in 1.74s
Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0
Expected Behavior
No failures
Although this might somehow being expected behavior, it has its effects applications as the VSCode-Adapter, see: https://github.com/pester/vscode-adapter/issues/286
I'm going to guess this is because the using is in a different scope than the test scriptblock when it is run. The using ends up being part of the "discovery" phase, wheres the execution is part of the "run" phase.
I tried a couple workarounds like dot-sourcing the script with using namespace in it, oddly it didn't work.
using namespace is global to the session, so that's why it works after you run it once, but not in a new session.
Not sure this is something that could be fixed in Pester, as it's a core PowerShell parsing issue (I think there's a feature request somewhere to allow using namespace at the top of scriptblocks for the parser but it'll probably not happen for a while if ever)