Mocking Response of a REST API in Pester

590 Views Asked by At

I have a PowerShell script that returns a string from a REST API call. I am using

$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'

return $Response.ToString() 

I am able to mock the request but I should also be able to mock the response so that it returns a dummy string value for $Response. Currently I get an error RuntimeException: You cannot call a method on a null-valued expression.

I have tried the below code as a response but i get the same error.

Mock Invoke-RestMethod -MockWith{return "abc"}

Any thoughts?

2

There are 2 best solutions below

0
Mark Wragg On BEST ANSWER

I can't see any issue with what you're trying to do. This works for me:

BeforeAll {
    function Invoke-API ($URI, $Body) {
        $Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'
        return $Response.ToString()
    } 
}

Describe 'Tests' {

    BeforeAll {
        Mock Invoke-RestMethod { return 'abc' }
    }

    It 'Should return a response' {
        Invoke-API -Uri 'http://fake.url' -Body 'test' | Should -Be 'abc'
    }
}
1
Jasper On

I had this situation when I used the Invoke-RestMethod in a Module. I wanted to mock it but it didn't. Had to specify the module name of my own module (not the PowerShell.Utility) and then it worked.

Edit:

File to test: TestModule.psm1

Pester file: TestModule.Tests.ps1 containing:

$moduleName = "TestModule" 
Mock -ModuleName $moduleName -CommandName Invoke-RestMethod -MockWith {
   throw $exceptionObj  
}