Author Posts

August 24, 2017 at 9:45 pm

Hi Everyone,

I am having some trouble trying to mock a cmdlet within my function; specifically the Invoke-WebRequest. Each time I mock this command within my pester command it fails. How do I know it fails. Within my function I assign $content variable to the result of the Invoke-Webrequest. And my mock is written as such Invoke-Webrequest -modulename Mymodule -mockwith { return 'Content' = 'content']

When executing the test I receive my Write-Warning message "Invoke-WebRequest to test failed"

Can anyone provide me with an example to mock a similar scenario or provide one? I have looked at 3 other examples online and I have tried their methods to no avail. I cannot figure out what I am doing incorrectly.

Thanks!

August 24, 2017 at 11:05 pm

I don't think there's anything special about Invoke-WebRequest. Here's a snippet tested and it was mocked as expected.

function foo {
	param()
	Invoke-WebRequest -UseBasicParsing -Uri 'somefakeurihere'
}

describe 'test' {
	mock 'Invoke-WebRequest' {
		'invoke-webrequest mocked'
	}

	$result = foo

	it 'should return mocked string' {
		$result | should be 'invoke-webrequest mocked'
	}
	
	it 'should be mocked' {
		$assMParams = @{
			CommandName = 'Invoke-WebRequest'
			Times = 1
			Exactly = $true
		}
		Assert-MockCalled @assMParams
	}
}