Jest:在测试块之间共享异步代码 [英] Jest: shared async code between test blocks

查看:13
本文介绍了Jest:在测试块之间共享异步代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的测试代码:

I have some test code like this:

test('Test', async () => {
  const someData = await setup()
  const actual = myFunc(someData.x)
  expect(actual.a).toEqual(someData.y)
  expect(actual.b).toEqual(someData.y)
  ... many more like this
}

我想将代码分解成多个 test 块(因为我什至无法为每个 expect 语句添加描述消息).

I would like to break apart the code into multiple test blocks (because I can't even add a description message to each expect statement).

如果 Jest 支持异步 describe,我可以这样做:

If Jest supported async describe, I could do this:

describe('Some group of tests', async () => {
const someData = await setup()

test('Test1', async () => {
  const actual = myFunc(someData.x)
  expect(actual.a).toEqual(someData.y)
}

test('Test2', async () => {
  const actual = myFunc(someData.x)
  expect(actual.b).toEqual(someData.y)
}
})

我当然可以为每个测试重复设置调用,但这会大大减慢测试速度(我在那里填充 MongoDB).

I could duplicate the setup call for each test of course, but that would slow down the test considerable (I'm populating MongoDB there).

那么,我可以通过 Jest 改进测试的结构吗?

So, any way I can improve the structure of my test with Jest?

推荐答案

describe 回调函数不应该是异步的,这是正确的.它为套件同步定义测试,其范围内的任何异步操作都将被丢弃.

It's correct that describe callback function isn't supposed to be asynchronous. It synchronously defines tests for a suite, any asynchronous operations in its scope will be discarded.

以前 Jasmine 和 Jest 允许使用常规函数和 this 访问公共测试上下文.此功能在 Jest 中已被弃用;公共变量需要用户自定义.

Previously Jasmine and Jest allowed to access common test context with regular functions and this. This feature was deprecated in Jest; common variables need to be user-defined.

共享代码可以移动到内部使用 beforeAllbeforeEach 等的辅助函数中:

Shared code can be moved into helper function that internally uses beforeAll, beforeEach, etc:

const setupWithTestContext = (testContext = {}) => {
  beforeAll(async () => {
    const setupData = await setup();
    Object.assign(testContext, setupData);
  });
  return testContext; // sets up a new one or returns an existing
});

const anotherSetupWithTestContext = (testContext = {}) => {
  beforeEach(() => {
    testContext.foo = 0;
  });
  return testContext;
});

...

describe('Some group of tests', async () => {
    const sharedTestData = setupTestContext();
    // or
    // const sharedTestData = {}; setupTestContext(sharedTestData);

    anotherSetupWithTestContext(sharedTestData);

    test('Test1', async () => {
      // context is filled with data at this point
      const actual = myFunc(sharedTestData.x)
      ...
    }
    ...
})

这篇关于Jest:在测试块之间共享异步代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆