gpt4 book ai didi

javascript - 开 Jest : return a value from a test

转载 作者:行者123 更新时间:2023-11-28 17:27:09 25 4
gpt4 key购买 nike

我想使用 Jest 在另一个测试(下一个测试)中获取一个测试的结果(返回值)。有办法做到这一点吗?

我尝试返回一个值,但我现在不知道如何捕获它并将其影响为 const 或 var。

test('a', () => {
expect(1).toBe(1)
return 'ok'
})

test('b', () => {
// I want to use the value returned by the first test: "ok"
})

我知道我可以使用“全局”变量,但我觉得它有点hacky。

有没有办法获取测试回调的返回值以便在另一个测试中使用它?

最佳答案

对于单次执行,您可以拥有一个存储执行信息的顶级对象,您可以在 afterAll 方法中解析该信息。

这是一个虚拟测试套件,它强调了我的意思。当然,您可以发挥创意,更有条理,甚至可以拥有更高级别的对象。

然后您可以将它们存储在文件中,将结果发送到服务器等。

test.js

describe('A suite', () => {

let suiteSpecificData = {};

test('a test', () => {
expect(1).toBe(1)
suiteSpecificData["a test"] = "ok"
})

test('another test', () => {
let theOtherTestData = suiteSpecificData["a test"];
let thisTestData = suiteSpecificData["another test"] = {};

if (theOtherTestData === "ok") {
thisTestData.messageOne = "All good with the other test";
thisTestData.someMoreRandomStuff = [1,2,3];
}
})

afterAll(() => {
console.log(JSON.stringify(suiteSpecificData));
});
});

关于javascript - 开 Jest : return a value from a test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51300701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com