Functions/Install-NodePackageRequiredModules.Tests.ps1

describe "BitTitan.Runbooks.Common/Install-NodePackageRequiredModules" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Install-NodePackageRequiredModules.ps1"

    # Declare external functions and mocks
    mock Get-Location {}
    mock Set-Location {}
    mock Out-File {}
    mock Invoke-Expression {
        $Global:LastExitCode = 0
    }

    context "when there are no issues" {

        it "indicates that the installation was a success" {
            # Call the function
            $output = Install-NodePackageRequiredModules -Name "name" -Details "details" -NodePackagePath "C:\temp" -ReturnInformation

            # Verify mocks
            Assert-MockCalled Invoke-Expression -Times 1 -Exactly -ParameterFilter {
                $Command -eq "cmd /c npm install '2>&1'"
            } -Scope it

            # Verify output
            $output.Success | Should Be $true
            $output.Result | Should BeNullOrEmpty
        }
    }

    context "when the installation fails with an exit code" {
        # Declare mocks
        mock Invoke-Expression {
            $Global:LastExitCode = 1
            "Error output"
        }

        it "outputs an error" {
            # Call the function
            $output = Install-NodePackageRequiredModules -Name "name" -Details "details" -NodePackagePath "C:\temp" -ReturnInformation `
                -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify mocks
            Assert-MockCalled Invoke-Expression -Times 1 -Exactly -ParameterFilter {
                $Command -eq "cmd /c npm install '2>&1'"
            } -Scope it

            # Verify output
            $output.Success | Should Be $false
            $output.Result | Should Be "Error output`r`n"
            $errorVariable | Should Not BeNullOrEmpty
        }
    }

    context "when the installation throws an exception" {
        # Declare mocks
        mock Invoke-Expression {
            throw "up"
        }

        it "outputs an error" {
            # Call the function
            $output = Install-NodePackageRequiredModules -Name "name" -Details "details" -NodePackagePath "C:\temp" -ReturnInformation `
                -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify mocks
            Assert-MockCalled Invoke-Expression -Times 1 -Exactly -ParameterFilter {
                $Command -eq "cmd /c npm install '2>&1'"
            } -Scope it

            # Verify output
            $output.Success | Should Be $false
            $output.Result | Should BeLike "Exception occurred*up"
            $errorVariable | Should Not BeNullOrEmpty
        }
    }

}