Skip to content

Suggested Documentation Update: Mock Scope #1416

Description

@Veretax

1. General summary of the issue

Mock scope appears to be not intuitive.

If you define a Mock in an It, and think that when the It is gone that the Mock is gone, it does not appear to be so. Since there doesn't appear to be a way to dispose of the Mock, the Mock may be available in every It and its parent Context.

The Work around is to put non mocked tests in a separate Context or Describe

2. Describe Your Environment

Happens in both Win 10 and Server 2016
Pester 4.9.0

Operating System, Pester version, and PowerShell version:

Pester version     : 4.9.0 C:\Program Files\WindowsPowerShell\Modules\Pester\4.9.0\Pester.psd1
PowerShell version : 5.1.14393.3053
OS version         : Microsoft Windows NT 10.0.14393.0

If you use Pester from a folder not included in the Env:PSModulePath please change a provided code accordingly.

3. Expected Behavior

I expected one of two things:

Either 1. Mocks are no longer available when defined in an it and the it is done.
2, A method to dispose of the Mock when done with it.

4.Current Behavior

Right now Mocks defined in an It, override the mocked call in all other its within the same context.
To test you have to create a second context. Not clear from documentation.

5. Possible Solution

Add a section on scoping to docs on wiki for Mocking, barring that add feature so that mocks can be disposed of

6. Context

The article published in 2014 here has a blurb about this issue: https://www.powershellmagazine.com/2014/09/30/pester-mock-and-testdrive/
Kudos to Jakub Jareš for this quote:

"Mock scoping
The last set of rules you should keep in mind are the scoping rules that apply to mocks and mock call assertions. They complicated our lives already when we tried to assert on a mock call count in the first example, and they may produce all kinds of unexpected results if you are not aware of them:

Mock defined in Describe is available in the whole Describe.
Mock defined in Context is available in the whole Context.

Mock defined in It is available in its parent scope. That is in whole Context if the It is placed in a Context, and in whole describe if the It is placed in a Describe."

THere is a section about 'Invoke-Pester' but it would be smart to add a section called Scoping that points to it to make the docs better.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions