如何在单独的文件中为 jest.each 定义测试装置?

How can I define test fixtures for jest.each in a separate file?

在对关注点分离的永恒追求中,我想重写我的玩笑测试并将用于测试的所有数据移出到一个单独的文件中。示例:

describe('something', () => {
    it.each`
        key       | value
        ${'foo'}  | ${{
            'this': ['is', 'a'],
            'long': ['js', 'object']
        }}
        ${'bar'}  | ${{
            'i': ['don\'t', 'want'],
            'all': ['this', 'stuff'],
            'in': ['my test file']
        }}
    `("should work as expected for '$key'", async ({key, value}) => {
        // Test logic goes here
        actual = doSomething(key)
        actual.shouldEqual(value)
    })
})

相反,我宁愿写这样的东西:

describe('something', () => {
    it.each('test/something-data.json', "should work as expected for '$key1'", async ({key1, key2}) => {
        // Test logic goes here
        actual = doSomething(key)
        actual.shouldEqual(value)
    })
})

然后会在单独的文件中声明我所有的固定装置 test/something-data.json

jest目前有什么办法可以实现吗?当然,我可以从文件中手动读取灯具,但这不会让我看到每个灯具的单一成功或失败。或者这会是未来对 jest 的功能请求吗?

可以实现,只需要require json 文件

例如

it.each(
  require("./test/something-data.json")
)("should work as expected for '%s'",
  ({ key1, key2 }) => {
    // Test logic goes here
    expect(doSomething(key)).toEqual(value);
  }
);

working example