src/functions/Export-RegentRecordsByFind.Tests.ps1

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"

Describe "Export-RegentRecordsByFind" {
  Context -Name "Given a config file, and that Microsoft.Xrm.Data.Powershell is installed" {
    $params = @(
      @{
        CrmInstance = "CRMRECRUIT";
        ViewName    = "TestView";
        IsUserView  = $true;
        ExportPath  = "TestDrive:/test1.json"
      },
      @{
        CrmInstance = "CRMRECRUITTEST";
        ViewName    = "OtherTestView";
        IsUserView  = $false;
        ExportPath  = "TestDrive:/test2.json"
      }
    )
    $configPath = "TestDrive:\config.json"
    $params | ConvertTo-Json > $configPath

    # A deeply nested object, so as to show how the JsonDepth parameter works
    Set-Variable -Name "resultToReturn" -Option Constant -Scope Script @{foo = @{
        bar = @{
          bam = @{
            baz = @{
              wing = "ding"
            }
          }
        }
      } 
    }
    Mock -CommandName Get-CrmRecordsByViewName -Verifiable -MockWith {return $resultToReturn}
    
    It "Should execute Get-CrmRecordsByViewName for each config" {
      Export-RegentRecordsByFind -PathToConfig $configPath
      Assert-MockCalled -Scope It -CommandName Get-CrmRecordsByViewName `
      -Exactly 1 `
      -ParameterFilter { $ViewName -eq "TestView" }
      Assert-MockCalled -Scope It -CommandName Get-CrmRecordsByViewName `
      -Exactly 1 `
      -ParameterFilter { $ViewName -eq "OtherTestView" }
    }
    It "Should write the results to the export path, using the correct JsonDepth" {
      Export-RegentRecordsByFind -PathToConfig $configPath -JsonDepth 10
      $result1 = Get-Content "TestDrive:\test2.json" | ConvertFrom-Json
      $result1.foo.bar.bam.baz.wing | Should -Be $resultToReturn['foo']['bar']['bam']['baz']['wing']
      Export-RegentRecordsByFind -PathToConfig $configPath -JsonDepth 2
      $result2 = Get-Content "TestDrive:\test2.json" | ConvertFrom-Json
      $result2.foo.bar.bam | Should -Be "System.Collections.Hashtable"
    }
    
    It "Should accept a parameter object as input" {
      Export-RegentRecordsByFind -ParameterObject $params[0]
      Assert-MockCalled -CommandName Get-CrmRecordsByViewName -Scope It -Exactly 1 -ParameterFilter { $ViewName -eq "TestView" }
    }
    It "Should also accept hashtables or pscustomobjects as parameters from the pipeline" {
      $params[0] | Export-RegentRecordsByFind
      Assert-MockCalled -CommandName Get-CrmRecordsByViewName -Scope It -Exactly 1 -ParameterFilter { $ViewName -eq "TestView" }
      New-Object psobject -Property $params[0] | Export-RegentRecordsByFind
      Assert-MockCalled -CommandName Get-CrmRecordsByViewName -Scope It -Exactly 2 -ParameterFilter { $ViewName -eq "TestView" }
    }
  }
}