1

1. Provide a general summary of the issue in the Title above

2. Describe Your Environment

Pester version     : 4.3.1 /usr/local/share/powershell/Modules/Pester/4.3.1/Pester.psm1
PowerShell version : 6.0.1
OS version         : Unix 16.7.0.0

3. Expected Behavior

Expected that the mocked function would be called, more information below.

4.Current Behavior

I'm attempting to mock a function in a nested module. The file structure is such:

Module
│   Module.psd1
│ 
└───NestedModule1
│   │   NestedModule1.psm1
│ 
└───NestedModule2
│   │   NestedModule2.psm1
│ 
└───NestedModule3
│   │   NestedModule3_1.psm1
│   │   NestedModule3_2.psm1
│   │   NestedModule3_3.psm1

I'm running a function within NestedModule1.psm1 that calls a function in NestedModule2.psm1. I would like the function in NestedModule2.psm1 to return an error code (defined on our end as just '99') so I attempeted to Mock it using

Mock NestedModule2_function {return "99"} -ModuleName NestedModule1

I would expect back that this mocked function would be called, so I used the function below to check that:

Assert-MockCalled NestedModule2_function

From this function I receive back RuntimeException: You did not declare a mock of the NestedModule2_function Command.

I would've expected that this got called exactly once, but it seems like the error is saying that I didn't mock the function at all, or didn't mock it correctly at least. I also attempted to remove the Assert-MockCalled and see if it runs, and it uses the non-mocked function.

We've gotten the mock function to work before with non-nested functions but haven't had much luck with it. I did attempt to make sure that the root module was at least '*.psm1' per the README for Pester.

5. Possible Solution

I attempted to look at some other open issues regarding mocking and mocking nested modules specifically, https://github.com/pester/Pester/issues/204. However I wasn't able to get anything that I could get the code to work with it.

6. Context

I'm not able to use Pester effectively to test my PowerShell code.

Related Github Issue Opened here: https://github.com/pester/Pester/issues/1017

sschrass
  • 7,014
  • 6
  • 43
  • 62

1 Answers1

0

Make sure you explicitly import the nested module with Import-Module in your pester test file.

Import-Module NestedModule1 #necessary for mocks to work, even though this may already be implicitly imported by Module.
Import-Module NestedModule2
Import-Module NestedModule3
Import-Module Module

Mock NestedModule2_function {return "99"} -ModuleName NestedModule1

Describe <test name> {
    <my test block>
}

I haven't found a clear explanation of this in Pester documentation, but discovered it in my own troubleshooting.

jschmitter
  • 1,669
  • 19
  • 29
  • I experienced this on Windows with Powershell 5.x, so I'm curious if my solution works for you on Unix PS 6.x – jschmitter Sep 24 '18 at 19:04