I want to mock the results from Get-ChildItem but keep getting issues. How do I mock in Pester?
It 'Test get latest version' {
Mock -CommandName 'Test-Path' –MockWith {
return $true
}
Mock -CommandName 'Get-ChildItem' –MockWith {
$MockedListOfDirectories = `
'test_1.0.1.1', `
'test_1.1.10.5', `
'test_1.1.10.1', `
'test_1.2.18.1', `
'test_1.4.7.0'
return $MockedListOfDirectories
}
}
The output from the tests:
PSInvalidCastException: Cannot convert the "â€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
ArgumentTransformationMetadataException:
Cannot convert the "â€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
ParameterBindingArgumentTransformationException: Cannot process argument transformation on parameter 'MockWith'. Cannot convert the "â€MockWith {
return True
}
Mock -CommandName 'Get-ChildItem' â€MockWith" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
at <ScriptBlock>, C:\my\path\to\file.ps1:8
CodePudding user response:
It looks like the error you are seeing is because -MockWith
is using an em-dash instead of a dash. This can happen sometimes if you've copied an example from a webpage.
Ensuring the dashes are non em-dash and your code works fine for me, although for it to be a complete test you need to actually do some testing that then invokes your Mocks, for example:
Describe 'tests' {
It 'Test get latest version' {
Mock -CommandName 'Test-Path' -MockWith {
return $true
}
Mock -CommandName 'Get-ChildItem' -MockWith {
$MockedListOfDirectories = `
'test_1.0.1.1', `
'test_1.1.10.5', `
'test_1.1.10.1', `
'test_1.2.18.1', `
'test_1.4.7.0'
return $MockedListOfDirectories
}
Test-Path -Path 'fakepath' | Should -Be $true
Get-ChildItem | Should -Contain 'test_1.1.10.5'
}
}