【问题标题】:Is there a Javascript equivalent to pytest's parameterized fixtures?是否有与 pytest 的参数化装置等效的 Javascript?
【发布时间】:2018-05-21 09:42:35
【问题描述】:

在 pytest 中,您可以设置可以具有多个不同值的固定装置。这些被称为“参数化夹具”。使用这些fixture 的测试将使用这些fixture 中所有可能的值组合运行。

示例

# Fixture `a` can have the values `1` and `2`
@pytest.fixture(params=[1, 2])
def a(request):
    yield request.param

# Fixture `b` can have the values `3` and `4`
@pytest.fixture(params=[3, 4])
def b(request):
    yield request.param

# The test `test_sum` uses the fixtures `a` and `b`
def test_sum(a, b):
    assert sum([a, b]) == a + b

这里,函数test_sum 将总共运行四次。每次运行将使用不同的参数:a=1, b=3a=1, b=4a=2, b=3a=2, b=4

问题

在任何 Javascript 测试库中是否有等效于参数化的装置? (我们目前使用的是 mocha,所以这对我们来说是最有趣的)

【问题讨论】:

  • 我正在寻找同样的东西。令人惊讶的是,pytest 的fixture 相似功能是requested for years。然而,这些 JS 测试前沿从来没有真正理解使用内置夹具时测试的优雅程度。

标签: javascript unit-testing mocha.js pytest


【解决方案1】:

Jest 现在将该实用程序合并到其代码库中:) 它位于 it.each/test.each 下。对于旧版本的 jest,您可以使用下面提到的库之一。

旧答案:

最近,我发现有一个用于 Jest 的实用程序,名为 jest-each 或语法不太好的 jest-in-case,这是 pytest.mark.parametrized 的一个很好的替代品。

下面的旧旧原始答案:

很遗憾,没有。从我在互联网上发现的内容来看,即使在今天,摩卡也不支持它。这种语法也有rejected proposal(s),但目前,唯一的解决方案是他们称之为dynamically generating tests,语法如下面的代码(取自文档)。此外,您还可以阅读有关sad state of JS vs. Python testing 的更多信息。

describe('Possible user names behaves correctly ', () => {
  const TEST_CASES = [
    {args: ['rj'], expected: false},
    {args: ['rj12345'], expected: false},
    {args: ['rj123'], expected: true},
  ]

  TEST_CASES.forEach((testCase) => {
    it(`check user name ${JSON.stringify(testCase.args)}`, () => {
      const result = checkUserName.apply(this, testCase.args)

      expect(testCase.expected).toEqual(result)
    })
  })
})

【讨论】:

    【解决方案2】:

    Playwright Test 测试框架借鉴了 PyTest 的这个概念;详情请见https://playwright.dev/docs/test-fixtures

    【讨论】:

      【解决方案3】:

      在遇到对 python 和 js 的参数化测试的需求后,我认为 Jest 中包含的.each 语法既易于使用又易读(抱歉,没有找到 Mocha 的选项!)。

      一个很好的例子可以在这里找到:https://dev.to/flyingdot/data-driven-unit-tests-with-jest-26bh

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-31
        • 2017-02-14
        • 2021-03-19
        • 1970-01-01
        • 2019-05-24
        • 1970-01-01
        • 2010-09-10
        • 2017-09-11
        相关资源
        最近更新 更多