Functions/Block-UntilExchangeOnlineUserAvailable.Tests.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
describe "BitTitan.Runbooks.ExchangeOnline/Block-UntilExchangeOnlineUserAvailable" -Tag "module", "unit" {

    # Import the function to test
    . "$($PSScriptRoot)\Block-UntilExchangeOnlineUserAvailable.ps1"

    # Declare external functions and mocks
    function Get-User {
        param ($Identity)
    }

    context "when the user is immediately available" {
        # Declare mocks
        mock Get-User {
            return [PSCustomObject]@{
                UserPrincipalName = "user@domain.com"
            }
        }

        it "returns the user after trying once" {
            # Call the function
            $output = Block-UntilExchangeOnlineUserAvailable -Identity "user@domain.com" -WaitLimitSeconds 20 -WaitIntervalSeconds 1

            # Verify the mocks
            Assert-MockCalled Get-User -Times 1 -Exactly -ParameterFilter {
                $Identity -eq "user@domain.com"
            } -Scope it

            # Verify the output
            $output.UserPrincipalName | Should Be "user@domain.com"
        }
    }

    context "when the user is available after several tries" {
        # Declare mocks
        $Global:numTries = 0
        mock Get-User {
            ++$Global:numTries
            if ($Global:numTries -ge 5) {
                return [PSCustomObject]@{
                    UserPrincipalName = "user@domain.com"
                }
            }
        }

        it "returns the user after trying several times" {
            # Call the function
            $output = Block-UntilExchangeOnlineUserAvailable -Identity "user@domain.com" -WaitLimitSeconds 20

            # Verify the mocks
            Assert-MockCalled Get-User -Times 5 -Exactly -ParameterFilter {
                $Identity -eq "user@domain.com"
            } -Scope it

            # Verify the output
            $output.UserPrincipalName | Should Be "user@domain.com"
        }
    }

    context "when the user is not available" {
        # Declare mocks
        mock Get-User {}

        it "returns null and outputs an error" {
            # Call the function
            $output = Block-UntilExchangeOnlineUserAvailable -Identity "user@domain.com" -WaitLimitSeconds 5 `
                -ErrorAction SilentlyContinue -ErrorVariable errorVariable

            # Verify the output
            $errorVariable | Should Not BeNullOrEmpty
            $output | Should Be $null
        }
    }
}