簡體   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