Pester Invoke-WebRequest

This topic contains 1 reply, has 2 voices, and was last updated by  Adam Bertram 3 months, 3 weeks ago.

  • Author
    Posts
  • #78033

    Michael
    Participant

    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!

  • #78039

    Adam Bertram
    Moderator

    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
    	}
    }
    

You must be logged in to reply to this topic.