繁体   English   中英

如何使用 Jest 正确实现这样的测试套件架构?

[英]How to correctly achieve such test suite archtecture with Jest?

我已经检查了 Jest 文档网站上的所有指南示例,但没有找到任何可以为我的问题提供答案的东西。

我正在寻找一种模式,它允许我使用 Jest 分别为许多不同的功能(在我的情况下是 getter)运行测试用例。

至于现在,在我的example.test.ts文件中,我有以下内容:

import { getterOne, getterTwo, getterThree, ... } from getters;

describe('test suite', () => {
  beforeAll(async () => {
    //connect to MongoDB
  })

  afterAll(async () => {
    //disconnect from MongoDB
  })

  //request token from DB, to check it
  it('key', async () => {
    const key = await KeysModel.findOne(_id: 'any').lean();
    expect(key).toMatchSnapshot({
      field: expect.any(String),
    });
  });

  /**
   * predefine key and some other things
   * but I can't call key here, because describe doesn't support
   * async/await, as it should be synchronous
   */


  //test separate getterOne with key variable as an argument

  //test separate getterTwo with key variable as an argument

  //test separate getterThree with key variable as an argument
})

但是众所周知,我不能在it案例中使用已经定义的键。 所以我可以在顶层再次定义 key ,但是

  • 是否可以为每个getter测试用例重新定义关键变量? 如果我有这么多吸气剂,我将有xN绝对无用的请求。
  • 据我了解,我无法在describe使用async/await ,因为不支持从“describe”返回 Promise。 测试必须同步定义

所以我不是在问,如何编写代码,而是在这样的场景中编写依赖测试用例的正确模式是什么?

有人可以提供一个例子吗? 我应该在describe里面写更多的test还是通常的做法有点不同?

应该使用哪些 Jest 方法以及使用顺序?

至于现在,我通过let关键字声明空变量,并使用它们,如下所示:

describe('test suite', () => {
  beforeAll(async () => {
    //connect to MongoDB
  })

  afterAll(async () => {
    //disconnect from MongoDB
  })

  describe('inside', () => {
    let key;

    beforeAll(async () => {
      key = await KeyModel.findOne();
    })
   
    test('getterOne', async () => {
      const res = await getterOne(key);
      expect(res).toMatchSnapshot({
        id: expect.any(Number)
      });
    });

    //other test with keys..
  
  })
})

它是否认为是一种好习惯?

至于现在,我正在使用与建议相同的结构。 但我也感谢Estus Flask为我指明了这个方向。 我不使用模型,主要是因为我不仅测试functions ,还测试数据库存在和数据持久性。

describe('test suite', () => {
  beforeAll(async () => {
    //connect to MongoDB
  })

  afterAll(async () => {
    //disconnect from MongoDB
  })

  /**
   * another describe stage below
   * with its own after and before and describe stages
   */

})

暂无
暂无

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

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