pester / Pester

Pester is the ubiquitous test and mock framework for PowerShell.
https://pester.dev/
Other
3.08k stars 470 forks source link

Calling pester from a class #2548

Closed Stephanevg closed 1 month ago

Stephanevg commented 1 month ago

Checklist

What is the issue?

Hi!

This is a specific pester 4.9.0 issue. I know it is not supported anymore, but if you guys could just give me a hint at what I should look at in order to fix that would be really great!

I do have a class that contains a method that does the following:

Class PesterTestHelper {
    [object]$TestData
    [String[]]$Path
    [String]$Version = "Latest"

    TestHelper(){}

    [void] InvokeTests([String[]]$Path) {
        #Accepts eithern a string or an array of strings that should be the path to the test script(s) or the folder containing test scripts.
        if([string]::IsNullOrEmpty($Path)){
            throw "No path provided for tests"
        }

        if($this.Version -eq 'Latest'){
            Import-Module -Name Pester -Force
        }else{
            Import-Module -Name Pester -RequiredVersion $this.Version -Force
        }

        $this.Path = $Path
        $this.TestData = Invoke-Pester -Path $Path -PassThru -Show None
    }
#...
}

This class is than invoked from a function with the following lines.


    $TestHelper = [PesterTestHelper]::New()
    $TestHelper.SetVersion("4.9.0")
    $TestHelper.InvokeTests("C:\MyTests\")

(When invoked from the function, or directly instanciated in a script file, I do have the same error message).

With Pester 5 it works just as expected, but with Pester 4.9.0 I get the following error message.

Pester\SafeGetCommand: C:\Program Files\WindowsPowerShell\Modules\Pester\4.9.0\Functions\PesterState.ps1:74:49
Line |
  74 |  … $script:SafeCommands['New-Object'] = & (Pester\SafeGetCommand) -Name  …
     |                                            ~~~~~~~~~~~~~~~~~~~~~
     | The term 'Pester\SafeGetCommand' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, 
     | or if a path was included, verify that the path is correct and try again.
Enter-CoverageAnalysis: The property 'CommandCoverage' cannot be found on this object. Verify that the property exists and can be set.

Am I missing some prerequisites ? Should I do my call to pester in another way ?

Thanks a lot for your guidance!

Expected Behavior

IT should execute the pester tests without an error.

Steps To Reproduce

No response

Describe your environment

No response

Possible Solution?

No response

Stephanevg commented 1 month ago

Using -global on the Import-MOdule statement fixed this issue. Closing