测试块之间共享异步代码

测试块之间共享异步代码

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

问题描述

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

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)
      ...
    }
    ...
})

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

08-11 22:44