Pester: 无法访问父级作用域变量

4

我在 Pester 中有以下简单的测试:

# Name.Tests.ps1

$name = "foo"

Describe "Check name" {
  It "should have the correct value" {
    $name | Should -Be "foo"
  }
}

所以当我导航到包含测试脚本的文件夹并运行Invoke-Pester时,我期望测试通过。相反,我收到以下错误:

[-]检查名称应具有正确的值。预期为'foo',但得到了$null...

你有什么想法为什么会失败,为什么在It块中$name被设为null - 因为它来自父作用域,$name不应该仍然设置为foo吗?


@NekoMusume 当然可以使用 $global:name$script:name,但为什么需要全局/脚本作用域呢?在线示例似乎不需要这种作用域(例如:https://medium.com/charot/test-arm-templates-using-pester-azure-devops-837b5006c30c)。 - Khan
您有一个拼写错误,It "should have the correct value 没有结束引号。 - Nico Nekoru
感谢。更新了描述。 - Khan
2
这很可能是由于 Pester v5,其中预先发现了泄漏,影响了变量的作用域。 - Mark Wragg
好的,那么可能是个bug?无论如何,有没有关于如何修复作用域但不使用全局/脚本作用域的建议? - Khan
显示剩余3条评论
2个回答

7
Pester v5有新的规则需要遵循,其中之一是(https://github.com/pester/Pester#discovery--run):
将所有代码放入It、BeforeAll、BeforeEach、AfterAll或AfterEach中。 除非你有充分的理由这样做,否则不要直接将任何代码放入Describe、Context或文件顶部,除非将其包装在这些块中。
…… 所有错放的代码将在Discovery期间运行,并且它的结果在Run期间不可用。
因此,在Describe块内将变量赋值放置在BeforeAll或BeforeEach中应该可以使其正常工作:
Describe "Check name" {
  BeforeAll {
    $name = "foo"
  }
  It "should have the correct value" {
    $name | Should -Be "foo"
  }
}

感谢 @Mark Wragg 指引我正确的方向!

0

这是我需要做的:

#mine only happens during a foreach loop
$names = @("foo", "foo2")

Describe "Check name - all errors" {
    foreach($rec in $names)
    {
        It "should have the correct value" {
            $rec | Should -Be "foo"
        }
    }
}

#this is what i had to do to fix it :(
Describe "Check name - fixed" {
    foreach($rec in $names)
    {
        It "should have the correct value" -TestCases @(
            @{
                rec = $rec
            }
        ) {
            $rec | Should -Be "foo"
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接