Functions/Disconnect-SharePointOnline.Tests.ps1

describe "BitTitan.Runbooks.SharePointOnline/Disconnect-SharePointOnline" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Disconnect-SharePointOnline.ps1"

    # Declare mocks and external functions
    function Disconnect-SPOService {}

    context "when there are no issues" {
        # Declare mocks
        mock Disconnect-SPOService {}

        # Set the connection
        $Global:SharePointOnlineConnectionEstablished = $true

        it "disconnects from SharePoint Online" {
            # Call the function
            $output = Disconnect-SharePointOnline

            # Verify the mocks
            Assert-MockCalled Disconnect-SPOService -Times 1 -Exactly -Scope it

            # Verify the output
            $Global:SharePointOnlineConnectionEstablished | Should Be $false
            $output | Should Be $true
        }

        # Reset the connection
        $Global:SharePointOnlineConnectionEstablished = $false
    }

    context "when there is no open connection" {
        # Declare mocks
        mock Disconnect-SPOService {}

        # Set the connection
        $Global:SharePointOnlineConnectionEstablished = $false

        it "does not disconnect and outputs a warning message" {
            # Call the function
            $output = Disconnect-SharePointOnline -WarningAction SilentlyContinue -WarningVariable warningVariable

            # Verify the mocks
            Assert-MockCalled Disconnect-SPOService -Times 0 -Exactly -Scope it

            # Verify the output
            $warningVariable | Should Not BeNullOrEmpty
            $Global:SharePointOnlineConnectionEstablished | Should Be $false
            $output | Should Be $true
        }

        # Reset the connection
        $Global:SharePointOnlineConnectionEstablished = $false
    }

    context "when an exception is thrown while disconnecting" {
        # Declare mocks
        mock Disconnect-SPOService {
            throw "up"
        }

        # Set the connection
        $Global:SharePointOnlineConnectionEstablished = $true

        it "outputs an error message" {
            # Call the function
            $output = Disconnect-SharePointOnline -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the mocks
            Assert-MockCalled Disconnect-SPOService -Times 1 -Exactly -Scope it

            # Verify the output
            $errorVariable | Should Not BeNullOrEmpty
            $Global:SharePointOnlineConnectionEstablished | Should Be $true
            $output | Should Be $false
        }

        # Reset the connection
        $Global:SharePointOnlineConnectionEstablished = $false
    }
}