简体   繁体   English

开玩笑:从测试返回值

[英]Jest: return a value from a test

I would like to get the result (the returned value) of a test in another test (the next test) with Jest. 我想使用Jest在另一个测试(下一个测试)中获得测试的result (返回值)。 Is there a way to do this? 有没有办法做到这一点?

I tried to return a value, but I don't now how to catch it and affect it to a const or a var. 我试图返回一个值,但现在不介绍如何捕获它并将其影响为const或var。

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

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

I know i can use "global" variable, but I feel like it's a bit hacky. 我知道我可以使用“全局”变量,但是我觉得它有点笨拙。

Is there a way to get the returned value of a test callback in order to use it in another test? 有没有一种方法可以获取测试回调的返回值以便在另一个测试中使用它?

For a single execution, you could have a top level object that stores execution information, which you parse in an afterAll method. 对于单个执行,您可以具有一个存储执行信息的顶级对象,该信息在afterAll方法中进行解析。

Here is a dummy test suite which highlights what I mean. 这是一个虚拟测试套件,突出了我的意思。 Of course you can get creative and be more organized, and have objects even at a higher level. 当然,您可以变得更有创意,更有条理,甚至拥有更高层次的对象。

You could then store them in a file, send the results to a server, etc. 然后,您可以将它们存储在文件中,将结果发送到服务器等。

test.js 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));
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM