Functions/New-GSuiteUser.Tests.ps1
Describe "GSuite/New-GSuiteUser" -Tag "task", "unit" { # Import the function to test . "$($PSScriptRoot)\New-GSuiteUser.ps1" # Declare external functions and mocks function Invoke-RestMethod { param ($Uri, $Headers, $Method, $Body) return "user" } context "when there are no issues" { # Declare mocks mock Invoke-RestMethod { param ($Uri, $Headers, $Method, $Body) return "user" } # Declared the required global variable $Global:GSuiteAccessTokensHashTable = @{ User = "token" } it "creates a GSuite user" { # Call the function $output = New-GSuiteUser -PrimaryEmailAddress "user@domain.com" -FirstName "first" ` -LastName "last" -Password "Password1!" -ErrorAction SilentlyContinue -ErrorVariable errorVariable # Construct the expected request body $NewUserBody = @{ name = @{ familyName = "last" givenName = "first" } password = "Password1!" primaryEmail = "user@domain.com" } | ConvertTo-Json # Verify the mocks Assert-MockCalled Invoke-RestMethod -Times 1 -Exactly -ParameterFilter { $Uri -eq "https://www.googleapis.com/admin/directory/v1/users" -and $Headers.'Content-Type' -eq "application/json" -and $Headers.Accept -eq "application/json" -and $Headers.Authorization -eq "Bearer token" -and $Method -eq "POST" -and $Body -eq $NewUserBody } -Scope it # Verify the output $output | Should Be "user" $errorVariable | Should BeNullOrEmpty } # Reset the global variable to null $Global:GSuiteAccessTokensHashTable = $null } context "when `$Global:GSuiteAccessTokensHashTable is null" { it "throws an exception" { # Call the function { New-GSuiteUser -PrimaryEmailAddress "user@domain.com" -FirstName "first" -LastName "last" ` -Password "Password1!" -ErrorAction SilentlyContinue -ErrorVariable errorVariable } | Should -Throw } } context "when `$Global:GSuiteAccessTokensHashTable does not contain the user access token" { # Declared the required global variable $Global:GSuiteAccessTokensHashTable = @{ } it "throws an exception" { # Call the function { New-GSuiteUser -PrimaryEmailAddress "user@domain.com" -FirstName "first" -LastName "last" ` -Password "Password1!" -ErrorAction SilentlyContinue -ErrorVariable errorVariable } | Should -Throw } # Reset the global variable to null $Global:GSuiteAccessTokensHashTable = $null } } |